在构造函数中注入多个服务VS在构造函数中注入单个ServiceFactory

时间:2018-11-21 11:01:39

标签: c# dependency-injection unity-container

我想提示这两种解决方案之间最好的方法是什么

我统一使用N个服务接口/类

internal class Configurator
    {
        private static IUnityContainer container = new UnityContainer();

        internal static void Configure()
        {
            container.RegisterType<ICustomerService, CustomerService>();
            container.RegisterType<IPhoneService, PhoneService>();
            container.RegisterType<IUserService, UserService>();
            ...
        }

        internal static T Resolve<T>()
        {
            return container.Resolve<T>();
        }
    }

所有接口都实现IService的地方

public interface ICustomerService : IService
public interface IPhoneService: IService
public interface IUserService: IService

我还创建了一个ServiceFactory类

public class ServiceFactory : IServiceFactory
    {
        public T GetService<T>() where T : IService
        {
            return Configurator.Resolve<T>();
        }
    }

现在我的疑问是:

解决方案1:

public class TestViewModel
{
    private ICustomerService _customerService;

    private IPhoneService _phoneService;

    private IUserService _userService;

    public TestViewModel(ICustomerService customerService, IPhoneService phoneService, IUserService userService)
    {
        _customerService = customerService;
        _phoneService = phoneService;
        _userService = userService;
    }

解决方案2:

public class TestViewModel
{
    private IServiceFactory _serviceFactory;

    private IUserService _userService;
    public IUserService UserService
    {
        get
        {
            if(_userService == null)
                _userService = _serviceFactory.GetService<IUserService>();
            return _userService;
        }
    }

    public MainWindowViewModel(IServiceFactory serviceFactory)
    {
        _serviceFactory = serviceFactory;
    }

我个人更喜欢解决方案2,因为

1)如果必须在单个构造函数中注入大量服务,则只能注入工厂

2)仅在请求时初始化服务(在解决方案1中,如果用户永远不会调用/使用所有服务,则它们也都在构造函数中初始化)

您是否同意解决方案2更好?是否有禁忌症?我想听听您的一些看法...

1 个答案:

答案 0 :(得分:1)

ServiceFactory类基本上起着Service Locator的作用,被认为是一种反模式。原因是通过这种方式,您的服务可以拥有比所需更多的功能。通过在构造函数中声明您的依赖关系,您可以掌握严格的准则,以供您在类中使用和使用。

如果构造函数参数过多,则可能是代码味道,表明您的类可能做了比应做的更多的事情,并且可能违反了Single Responsibility Principle。在这种情况下,您应该考虑将此类重构为较小的子类,每个子类都执行较小的任务。

我的问题是第一个解决方案更好

相关问题