这是通过使用构造函数注入来避免 ServiceLocator 模式的正确方法吗?
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
使用我想避免的 ServiceLocator 消费类。
public class MyConsumingClass
{
public object DoSomething<TEntity>(TEntity entity)
where TEntity : class
{
var thing = ServiceLocator.Current.GetInstance<IEntitySomethingBase<TEntity>>();
}
}
使用 MEF 的解决方案。修改上面的 *EntitySomething's 以导出,并且
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();
}
}
实际上还没有尝试过,但想知道是否还有其他方法可以实现这一目标。
谢谢