首页 > 解决方案 > 如何在 ASP.NET Core 中注册此依赖项?

问题描述

public abstract class BaseClass<T> {
    private ISomeinterface _param;
    
    public BaseClass(ISomeinterface param) {
        _param = param;
    }
}

public class DerivedClass : BaseClass<Entity> {
    public DerivedClass(ISomeinterface param) : base(param) {}
}

如何在 ASP.NET Core 中注册此依赖项?

标签: c#asp.net-coredependency-injection

解决方案


AddScoped、AddTransient 和 AddSingleton 方法接收一个 serviceType 和 implementationType ,它们都被传递为Type,最后都插入到IServiceCollection 这里是实现

private static IServiceCollection Add(
      IServiceCollection collection,
      Type serviceType,
      Type implementationType,
      ServiceLifetime lifetime)
    {
      ServiceDescriptor serviceDescriptor = new ServiceDescriptor(serviceType, implementationType, lifetime);
      collection.Add(serviceDescriptor);
      return collection;
    }

因此,回答您的问题,您可以将泛型类型注册为服务,而不是作为实现,因为您无法创建泛型类型的实例。但是根据您的实现,您不能在没有在实现类型上指定泛型参数的情况下注册泛型类型。这应该失败

services.AddScoped(typeof(BaseClass<>), typeof(DerivedClass));

出现以下错误:

开放通用服务类型“BaseClass`1[T]”需要注册开放通用实现类型。(参数“描述符”)

请参阅下面的定义

public abstract class BaseClass<T>
{

    public BaseClass()
    {
    }
}

public class DerivedClass : BaseClass<Entity>
{
    public DerivedClass() : base() { }
}

public class DerivedClass2<T> : BaseClass<T> where T: Entity
{
   
}

public class Entity
{

}

现在这也应该可以完美地工作

services.AddScoped(typeof(BaseClass<>), typeof(DerivedClass2<>));

或者

services.AddScoped(typeof(BaseClass<Entity>), typeof(DerivedClass2<Entity>));

希望这可以帮助


推荐阅读