0

これは、コンストラクタインジェクションを使用して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'sto Export、および

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();
    }
}

実際にはまだ試していませんが、これを達成する他の方法はどこにあるのだろうかと考えていました。

ありがとう

4

1 に答える 1

1

If my understanding is correct, you need a factory

What you are trying to achieve has actually become really usual, and that's because the IoC containers resolve dependencies when the application starts up, and in most of the applications the dependencies required need to be injected based on some constraints.

Moderns IoC containers try to address this, like Guice for Java

Read this to get more information about factories:

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

What you need is a factory to create the correct type based on the parameter, and you can place a call to your service locator inside of your factory (I know you are using the service locator anti-pattern but you are moving it from your domain to the factory, a factory is only used to wire up objects so it's common to have calls to the IoC inside factories).

For reference:

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

于 2012-04-27T00:41:14.560 に答える