如何在C#中注入一个类(不是接口)?

Bla*_*ise 7 c# dependency-injection unity-container

我在这里使用Unity.但可能我们只需指向一个正确的方向.

我们知道如何注入接口:

public class AccountController:ApiController
{
    private readonly IAccountRepository _repository;

    public AccountController(IAccountRepository repository)
    {
        _repository = repository;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用RegisterType

var container = new UnityContainer();
container.RegisterType<IAccountRepository, AccountRepository>(new HierarchicalLifetimeManager());
Run Code Online (Sandbox Code Playgroud)

但是在我的AccountRepository中,我们将一个类注入到构造函数中.

private readonly ApplicationUserManager _userManager;
public AccountRepository(ApplicationUserManager userManager)
{
    _userManager = userManager;
}
Run Code Online (Sandbox Code Playgroud)

因此,在调用ApiController时,我仍然会收到此错误:

尝试创建"AccountController"类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.

堆栈跟踪:

System.Web.Http.Detpatcher.DefaultHttpControllerActivator.GetInstanceOrActivator上的System.Web.Http.Internal.TypeActivator.Create [TBase](Type instanceType)中的System.Linq.Expressions.Expression.New(Type type)(HttpRequestMessage请求,类型System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType)中的controllerType,Func`1和activator)

由于我已经创建了一些其他工作正常的ApiControllers,我想这一定是因为我们的ApplicationUserManager无法解析.

这里ApplicationUserManager继承自UserManager而不是接口.我不能用container.RegisterType<interface, derived_class>.解决问题的正确方法是什么?


这是ApplicationUserManager:

public class ApplicationUserManager : UserManager<User>
{
    public ApplicationUserManager(IdentityContext identityContext)
        : base(new UserStore<User>(identityContext))
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

正如下面的一些评论所示.这是RegisterType语句:

var container = new UnityContainer();
container.RegisterType<IAccountRepository, AccountRepository>(new HierarchicalLifetimeManager());
container.RegisterType<ApplicationUserManager, ApplicationUserManager>(new HierarchicalLifetimeManager());
container.RegisterType<IdentityContext, IdentityContext>(new HierarchicalLifetimeManager());

config.DependencyResolver = new UnityResolver(container);
Run Code Online (Sandbox Code Playgroud)

看起来设置ASP.NET Identity需要一些特殊的工作.我在这里找到一个链接: 为ASP.NET身份配置Unity DI.但到目前为止,我仍然无法使其发挥作用.

小智 0

您不需要这两行,因为 Unity 会为您解决它。

container.RegisterType<ApplicationUserManager, ApplicationUserManager>(new HierarchicalLifetimeManager());
container.RegisterType<IdentityContext, IdentityContext>(new HierarchicalLifetimeManager());
Run Code Online (Sandbox Code Playgroud)

for 的构造函数是什么IdentityContext样的?它很可能有一个您尚未注册的依赖项。如果它有多个构造函数,Unity 将选择参数数量最多的构造函数。