簡體   English   中英

Unity 注冊一個接口多個對象並告訴 Unity 在哪里注入它們

[英]Unity Register For One Interface Multiple Object and Tell Unity Where to Inject them

嗨,我一直無法告訴 Unity 對於一個接口,如果它有多個實現,我希望它將它們注入到不同的類中。這就是我的意思:

假設我有一個接口IProductCatalogService和兩個實現ProductCatalog : IProductCatalogServiceProductCatalogService : IProductCatalogService

我將如何告訴 Unity 類 AI 想要在我的構造函數中傳遞一個ProductCatalog類型的實例,而對於B類我想要一個ProductCatalogService的實例。

我在 ASP.NET Web API 項目中使用 Unity,並且在GLobalConfiguration中設置了解析器。

對於簡單的 1 對 1 注冊,一切正常。

這是我嘗試過的,但似乎不起作用:

public class DependencyServiceModel
{
    public Type From { get; set; }
    public Type To { get; set; }
    public IEnumerable<Type> ForClasses { get; set; }
}

public void RegisterTypeForSpecificClasses(DependencyServiceModel dependencyService)
{
    foreach (var forClass in dependencyService.ForClasses)
    {
        string uniquename = Guid.NewGuid().ToString();

        Container.RegisterType(dependencyService.From, 
            dependencyService.To, uniquename);

        Container.RegisterType(forClass, uniquename, 
            new InjectionConstructor(
                new ResolvedParameter(dependencyService.To)));
    }
}

DependencyServiceModel中, From是接口, To是我想要實例化的對象, ForClasses是我想要使用To對象的類型。

在下面的示例中,您有一個接口實現了兩次,並根據您的請求按需注入到兩個不同的客戶端類中。 訣竅是使用命名注冊。

class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<IFoo, Foo1>("Foo1");
        container.RegisterType<IFoo, Foo2>("Foo2");

        container.RegisterType<Client1>(
            new InjectionConstructor(new ResolvedParameter<IFoo>("Foo1")));
        container.RegisterType<Client2>(
            new InjectionConstructor(new ResolvedParameter<IFoo>("Foo2")));

        Client1 client1 = container.Resolve<Client1>();
        Client2 client2 = container.Resolve<Client2>();
    }
}

public interface IFoo {  }
public class Foo1 : IFoo {  }
public class Foo2 : IFoo { }

public class Client1
{
    public Client1(IFoo foo) { }
}

public class Client2
{
    public Client2(IFoo foo) { }
}

這很可能是您做錯的事情:

Container.RegisterType(forClass, uniquename, 
    new InjectionConstructor(
        new ResolvedParameter(dependencyService.To)));

您為具體類創建一個命名注冊。 相反,你應該有

Container.RegisterType(forClass, null, 
    new InjectionConstructor(
        new ResolvedParameter(dependencyService.To, uniquename)));

很高興知道。 如果你向一個接口注冊了多個類型,比如 belove;

container.RegisterType<ITransactionsService, EarningsManager>();
container.RegisterType<ITransactionsService, SpendingsManager>();

您無法獲取類型列表;

IEnumerable<ITransactionsService> _transactionsService;

列表中的此處將始終是最后注冊的類型(SpendingsManager。)

為了防止這種情況;

container.RegisterType<ITransactionsService, EarningsManager>("EarningsManager");
container.RegisterType<ITransactionsService, SpendingsManager>("SpendingsManager");

您必須以這種方式更改代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM