这是通过使用构造函数注入来避免服务定位器模式的正确方法吗?



这是通过使用构造函数注入避免服务定位器模式的正确方法吗?

public interface IEntitySomethingBase<TEntity>
{
    //Stuff
}
public class AccountEntitySomething : IEntitySomethingBase<Account>
{
    //Stuff
}
public class CustomerEntitySomething : IEntitySomethingBase<Customer>
{
    //Stuff
}
public class OrderEntitySomething : IEntitySomethingBase<Order>
{
    //Stuff
}
//Ditto, any number

使用我想要避免的服务定位器使用类。

public class MyConsumingClass
{
    public object DoSomething<TEntity>(TEntity entity)
        where TEntity : class
    {
        var thing = ServiceLocator.Current.GetInstance<IEntitySomethingBase<TEntity>>();
    }
}

使用 MEF 的解决方案。修改上面的*实体要导出的东西,以及

public class MyConsumingClass
{
    private List<Lazy<IEntitySomethingBase<Object>>> _things;
    [ImportingConstructor]
    public MyConsumingClass([ImportMany] List<Lazy<IEntitySomethingBase<Object>>> things)
    {
        _things = things;
    }
    public object DoSomething<TEntity>(TEntity entity)
        where TEntity : class
    {
        var thing = _things.Cast<IEntityInformationExtractor<TEntity>>().Where(t => t.GetType().FullName == entity.GetType().FullName).FirstOrDefault();
    }
}

实际上还没有尝试过,但想知道是否有其他方法可以实现这一点。

谢谢

如果我的理解是正确的,你需要一个工厂

您尝试实现的目标实际上已经变得非常普遍,这是因为 IoC 容器在应用程序启动时解析依赖项,并且在大多数应用程序中,需要根据某些约束注入所需的依赖项。

现代的IoC容器试图解决这个问题,就像Java的Guice

阅读本文以获取有关工厂的更多信息:

https://github.com/ninject/ninject.extensions.factory/wiki

您需要的是一个工厂来基于参数创建正确的类型,并且您可以在工厂内部调用服务定位器(我知道您正在使用服务定位器反模式,但您正在将其从您的域移动到工厂,工厂仅用于连接对象,因此通常在工厂内调用 IoC)。

供参考:

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

最新更新