I am well acquainted with the concepts of a service locator and dependency injection, but there is one thing that confuses me all the time, that is, to implement dependency injection for an application, we must use some kind of service locator at the beginning. Please consider the following code, let's say we have a simple DAL class:
public class UserProviderSimple : IUserProvider
{
public void CreateUser(User user)
{
}
}
And then in the Business Logig layer, we have a simple class that uses IUserProvider
, which is introduced using the constructor insert:
public class UserServiceSimple : IUserService
{
public IUserProvider UserProvider { get; set; }
public UserServiceSimple(IUserProvider userProvider)
{
UserProvider = userProvider;
}
public void CreateUser(User user)
{
UserProvider.CreateUser(user);
}
}
, , , , , , oneton :
public class ServiceLocator
{
private readonly UnityContainer _container;
private static ServiceLocator _instance;
public static ServiceLocator Instance()
{
if (_instance == null)
{
_instance = new ServiceLocator();
return _instance;
}
return _instance;
}
private ServiceLocator()
{
_container = new UnityContainer();
_container.RegisterType<IUserProvider, UserProviderSimple>();
_container.RegisterType<IUserService, UserServiceSimple>();
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
class Program
{
private static IUserService _userService;
private static void ConfigureDependencies()
{
_userService = ServiceLocator.Instance().Resolve<IUserService();
}
static void Main(string[] args)
{
ConfigureDependencies();
}
}
, , - , , ( )?