按名称属性

时间:2018-05-16 12:43:32

标签: c# autofac

假设我有2个接口:IProvider和IClient 现在我有4个班级,2个提供商和2个客户。每个客户都有一个带有IProvider的Construktor:

public interface IWebProvider : IProvider
{
}
public interface IDatabaseProvider : IProvider
{
}


public sealed class Client1 : ClientBase, IClient
{
        public Client1(IWebProvider provider) : base(provider) { }
}

public sealed class Client2 : ClientBase, IClient
{
        public Client2(IDatabaseProvider provider) : base(provider) { }
}

我的DI Bootstraper很简单:

private void Build()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<Provider>().As<IWebProvider>();
    builder.RegisterType<Provider2>().As<IDatabaseProvider>();
    builder.RegisterType<ConfigClient>().Named<IClient>("Web");
    builder.RegisterType<Client2>().Named<IClient>("Database");
    Container = builder.Build();
}

如何告诉Autofac在客户端1中使用Provider1,在Client2中使用Provider2而不创建不同的接口?我知道我可以为2个提供商创建一个新的接口作为代理作为一种解决方法,但也许我只是用错了。

使用KeyFilter的第二版

private void Build()
{
    var builder = new ContainerBuilder();
    // Providers for Access
    builder.RegisterType<Provider>().Keyed<IProvider>("DatabaseProvider");
    builder.RegisterType<Provider2>().Keyed<IProvider>("WebProvider");

    // Clients implementing the logic
    builder.RegisterType<Client>().Named<IClient>("Web").WithAttributeFiltering();
    builder.RegisterType<Client2>().Named<IClient>("Database").WithAttributeFiltering();
    Container = builder.Build();
}

public sealed class Client : ClientBase, IClient
{
    public Client([KeyFilter("WebProvider")] IProvider provider) : base(provider) { }
}

public sealed class Client2 : ClientBase, IClient
{
    public Client([KeyFilter("DatabaseProvider")] IProvider provider) : base(provider) { }
}

public sealed class Provider : ProviderBase, IProvider
{
    public Provider(){ }
}

public sealed class Provider2 : ProviderBase, IProvider
{
    public Provider2(){ }
}

此致 Lord_Pinhead

1 个答案:

答案 0 :(得分:2)

解决命名依赖关系的一种方法是using attributes

  

Autofac的元数据功能提供了一个KeyFilterAttribute,它允许您使用指定应使用哪个键控服务的属性来标记构造函数参数。

public sealed class Consumer
{
    public Consumer([KeyFilter("Web")] IClient client) { 
    }
}