没有服务定位器的工厂模式 [英] Factory pattern without service locator

查看:66
本文介绍了没有服务定位器的工厂模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前只能尝试编写不依赖服务位置的工厂类.

I am currently stuck at trying to write a factory class that doesn't rely on service location.

我唯一想到的另一种选择是使用构造函数注入来注入所有可能的实例,但是当类通过引用传递时,这可能会导致意外. 一旦可能的提供商数量增加,它也可能会变得昂贵且混乱.

The only other alternative I can think of is to use constructor injection to inject all possible instances, but that may lead to surprises as classes are passed via reference. It is also possibly going to be costly and messy once the number of possible providers grow.

提供程序本身是完全复杂的类,它们具有自己的依赖性,因此无法进行手动构造.

The providers themselves are full complex classes that have their own dependencies so manual construction is out of the picture.

更新的服务位置示例:

    public class ProviderFactory : IProviderFactory
    {
        private readonly IProviderConfigurationService _providerConfigurationService;

        public enum SearchType
        {
            Foo,
            Bar
        }

        public ProviderFactory(IProviderConfigurationService providerConfigurationService)
        {
            _providerConfigurationService = providerConfigurationService;
        }

        public Collection<IProvider> GetProviderInstances(SearchType searchType)
        {
            // Provider configuration service will read a XML/DB store to retrieve list of search providers applicable for a search type
            var providerList = _providerConfigurationService.GetProviderList(searchType);
            return new Collection<IProvider>(providerList.ForEach(x=> ServiceLocator.GetInstance(typeof(x))).ToList()) ;
        }
    }

我还有其他选择吗?我目前正在使用Unity for DI.

What are my other options? I am currently using Unity for DI.

推荐答案

另一种方法是将Func<Type, object>传递给构造函数,并通过您的容器实现该功能:

An alternative is to pass a Func<Type, object> to the constructor and to implement the function through your container:

unity.RegisterInstance<Func<Type, object>>(t => unity.Resolve(t))

然后在您的课程中:

public ProviderFactory(Func<Type, object> createFunc, IProviderConfigurationService pcs)
{
    _createFunc = createFunc; 
}

public Collection<IProvider> GetProviderInstances(SearchType searchType)
{
    var providerList = _providerConfigurationService.GetProviderList(searchType);
    return new Collection<IProvider>(providerList.Select(_createFunc).ToList());
}

这篇关于没有服务定位器的工厂模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆