簡體   English   中英

C#依賴注入多個相同泛型類型的實現

[英]C# dependency injection multiple implementation of the same Generic Type

注意:這不是重復的!

我有以下示例

public interface IRepository<TEntity> where TEntity : IEntity
{
...

}

public class Repository<TEntity> : IRepository<TEntity> where TEntity : IEntity
{
...

}

public class Repository<SpecialClass> : IRepository<SpecialClass> 
{

...
}


public class SpecialClass: IEntity
{
...
}

現在我想為每個IRepository<>使用Repository<>類,除了IRepository<SpecialClass>

// every IRepository<> :
services.AddScoped(typeof(IRepository<>), typeof(RepositoryEFCore<>));

// but not for SpecialClass
services.AddScoped(typeof(IRepository<SpecialClass>), typeof(Repository<SpecialClass>));

問題是,當接口已經為另一個類注冊時,如何為同一個接口注冊兩個(或多個)不同的類?

services.AddScoped(typeof(IRepository<>), typeof(RepositoryEFCore<>));

此行將在 DI 容器中添加所有 IRepository 處理程序。 為了從 DI 注冊中排除一些特殊的類,有一種使用反射的方法,

 Type[] handlers = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsClass && t.Name != "SpecialClass" &&  t.GetInterfaces().
        Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRepository<>))).ToArray();

        foreach (Type concreteHandler in handlers)
        {
            Type? handlerInterface = concreteHandler.GetInterfaces().First(i => i.GetGenericTypeDefinition() == typeof(IRepository<>));
            services.AddScoped(handlerInterface, concreteHandler);
        }

在這里,處理程序數組將保存 IRepository 的所有具體實現,不包括Specialclass,並且使用 foreach 您可以在 DI 中添加具有具體實現的所有對象。

暫無
暫無

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

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