如何使用StructureMap将不同的混凝土绑定到属性

时间:2017-08-08 14:41:42

标签: c# dependency-injection inversion-of-control structuremap

他们使用的是我正在工作的IoC的StructureMap。

我有一个应用程序类,它将实现同一个接口的多个属性......我需要绑定不同的实现

......不,我不能这样做:IProvider<T>

FOR INSTANCE:

    public class MyApplication
    {
        [SetterProperty]
        public IProvider OneProvider { get; set; }

        [SetterProperty]
        public IProvider TwoProvider { get; set; }
    }

    public class FooProvider: IProvider {
        // I would like to force this one to bind-on OneProvider ...
    }
    public class BarProvider: IProvider {
        // I would like to force this one to bind-on TwoProvider ...
    }

在Unity中,有很多方法可以做到这一点,例如;

[Dependency("FooProvider")]
public IProvider OneProvider { get; set; }

[Dependency("BarProvider")]
public IProvider TwoProvider { get; set; }

...但是,StructureMaps SetterProperty属性不允许这样做。

问题:
如何将不同的实现绑定到实例属性?

示例注册:
这是我的注册表可能是什么样子的一个例子......

public ContainerRegistry()
{
    Scan(
        scan =>
        {
            scan.TheCallingAssembly();
            scan.WithDefaultConventions();
            scan.LookForRegistries();
            scan.AssembliesFromApplicationBaseDirectory(f => f.FullName.StartsWith("My.Awesome.Company", true, null));
            scan.AddAllTypesOf(typeof(IApplication));
            scan.AddAllTypesOf(typeof(IManager<>));
            scan.AddAllTypesOf(typeof(IProvider));
            scan.AddAllTypesOf(typeof(IUnitOfWorkFactory<>));
            scan.SingleImplementationsOfInterface();
        });

    For(typeof(IApplication)).Use(typeof(MyApplication));
} 

1 个答案:

答案 0 :(得分:3)

更新

根据文档,您可以使用Inline Setter Configuration

  

下一节中的setter策略仍然可以填充   如果内联依赖项配置为匹配,则为StructureMap   setter属性,如下例所示:

public class MyApplication : IApplication {
    public IProvider OneProvider { get; set; }
    public IProvider TwoProvider { get; set; }
}


public class RuleWithSettersRegistry : Registry {
    public RuleWithSettersRegistry() {

        //...other code removed for brevity

        For<IApplication>().Use<MyApplication>()
            // I would like to force FooProvider to bind-on OneProvider        
            .Setter(x => x.OneProvider).Is<FooProvider>()
            // I would like to force BarProvider to bind-on TwoProvider
            .Setter(x => x.TwoProvider).Is<BarProvider>();            
    }
}

原始答案

如果您能够修改实现和目标类,那么尝试区分预期的依赖关系。

public interface IFooProvider : IProvider { }

public interface IFooProvider : IProvider { }

有实现

public class MyApplication {
    [SetterProperty]
    public IFooProvider OneProvider { get; set; }

    [SetterProperty]
    public IBarProvider TwoProvider { get; set; }
}

public class FooProvider: IFooProvider { }

public class BarProvider: IBarProvider { }

使用

注册所有IProvider派生实现时的方式
scan.AddAllTypesOf(typeof(IProvider));

它将获取预期的实现并绑定它们。