简体   繁体   English

在 netcore 中使用 autofac 的 registerType 异常

[英]registerType exception using autofac in netcore

This is not an issue, but a question.这不是问题,而是问题。 I have the following sample code:我有以下示例代码:

class CommonArgs{
}

class TestArgs : CommonArgs{
}

abstract class AbstractHandler where T: CommonArgs, new (){
}

class TestHandler: AbstractHandler{
}

I use autofac to register the type:我使用 autofac 来注册类型:

builder.RegisterType (typeof (TestHandler)). Named ("testHandler", typeof (AbstractHandler<>)). InstancePerLifetimeScope ();

When I build.Build () , I get an exception:当我build.Build () ,我得到一个异常:

System.ArgumentException: "The type 'TestHandler' is not assignable to service 'testHandler (AbstractHandler`1)'." System.ArgumentException:“类型‘TestHandler’不可分配给服务‘testHandler (AbstractHandler`1)’。”

What is the correct type of registration?什么是正确的注册类型? (use dotnet core Autofac 4.8.1) (使用dotnet core Autofac 4.8.1)

You were almost there, just use the RegisterType overload and a Named with some string key and a typeof(AbstractHandler<CommonArgs>))你快到了,只需使用RegisterType重载和带有一些字符串键和typeof(AbstractHandler<CommonArgs>))Named

Here is a link to my github with a small unit-test to issue your question.这是我的 github 的链接,其中包含一个小单元测试来发布您的问题。

Code:代码:

ContainerBuilder builder = new ContainerBuilder();            
builder.RegisterType<TestHandler>().Named("myTestHandler", typeof(AbstractHandler<CommonArgs>));

IContainer container = builder.Build();

var testHandler = container.ResolveNamed("myTestHandler", typeof(AbstractHandler<CommonArgs>));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM