【问题标题】:Autofac two properties with the same typeAutofac具有相同类型的两个属性
【发布时间】:2012-06-27 07:50:26
【问题描述】:

如果我在一个类中有两个具有相同接口类型的属性,并且我想向每个属性注入两个不同的具体类型,我该如何使用 autofac 进行属性或构造函数注入。

例如。

class A : IA
{
    public IB PropertyB { get; set; }
    public IB PropertyC { get; set; }

    public A(IB b, IB c)
    {
        PropertyB = b;
        PropertyC = c;
    }

    public void PrintB()
    {
        PropertyB.Print();
    }

    public void PrintC()
    {
        PropertyC.Print();
    }
}

我已经尝试过了,但当然我只是将 C 注入到这两个属性中

    var builder = new ContainerBuilder();

    builder.RegisterType<B>().As<IB>();
    builder.RegisterType<C>().As<IB>();
    builder.RegisterType<A>().As<IA>();

    var container = builder.Build();
    var a = container.Resolve<IA>();

或者这个结果相同:

    builder.RegisterType<B>().As<IB>();
    builder.RegisterType<C>().As<IB>();
    builder.RegisterType<A>().As<IA>().PropertiesAutowired();

    var container = builder.Build();
    var a = container.Resolve<IA>();

有没有办法告诉 autofac 我想要 PropertyB 中的 B 和 PropertyC 中的 C ?

【问题讨论】:

    标签: c# autofac


    【解决方案1】:

    使用属性注入,您可以执行以下操作:

    builder.RegisterType<A>()
        .As<IA>()
        .OnActivating(e =>
    {
        e.Instance.PropertyB = e.Context.Resolve<BImpl1>();
        e.Instance.PropertyC = e.Context.Resolve<BImpl2>();
    });
    

    【讨论】:

    • 嗨,感谢您的解决方案,但是当我尝试此操作时,当 autofac 尝试解析 B 或 C contrete 类型时出现 ComponentNotRegisteredException 错误。
    • 您必须使用 Autofac 显式注册具体类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    相关资源
    最近更新 更多