StructureMap:根据具体实例属性值有条件地使用具体类型

时间:2018-12-19 12:43:02

标签: c# structuremap

我正在努力使StructureMap使用共享公共接口的一种具体类型。所有候选对象都是中间抽象类的后代,这使情况进一步复杂化。

public interface ICustomer
{
    string Id { get; }
}

public abstract class CommonCustomer : ICustomer {
    public abstract string Id { get; }
}

// Fallback type if none matched
public class BaseCustomer : CommonCustomer
{
    public override string Id { get; } = "Base";
}

// Concrete type 1
public class AlphaCustomer : CommonCustomer
{
    public override string Id { get; } = "Alpha";
}

// Concrete type 2
public class BravoCustomer : CommonCustomer
{
    public override string Id { get; } = "Bravo";
}

到目前为止我尝试过的事情:

Scan(x =>
{
    x.TheCallingAssembly();
    x.AddAllTypesOf<ICustomer>();
});

var key = "Alpha";

For<ICustomer>().Use("",
    context => context.GetAllInstances<ICustomer>()
        .FirstOrDefault(x => x.Id == key)).Singleton();
For<ICustomer>().UseIfNone<BaseCustomer>().Singleton();

如何根据其字符串属性选择具体类型?以及如何浏览未直接实现ICustomer的类型?

1 个答案:

答案 0 :(得分:0)

您想要创建一个实例化ICustomer的工厂的声音。

public interface ICustomerFactory
{
    ICustomer Create(string key);
}

public class CustomerFactory : ICustomerFactory
{
    private readonly IContainer _container;
    public CustomerFactory(IContainer container)
    {
        _container = container;
    }
    public ICustomer Create(string key) => _container.TryGetInstance<ICustomer>(key);
}

在配置容器时将其命名:

var container = new Container(c =>
{
    c.For<ICustomerFactory>().Use<CustomerFactory>();
    c.Scan(x =>
    {
        x.TheCallingAssembly();
        x.AddAllTypesOf(typeof(ICustomer))
            .NameBy(t => ((ICustomer)Activator.CreateInstance(t, new object[0], new object[0])).Id);
    });
});

用法:

ICustomerFactory factory;
var customer1 = factory.Create("Alpha");
var customer2 = factory.Create("Bravo");
var customer3 = factory.Create("Base");
var customer4 = factory.Create("NotExisting"); // returns null.