英文:
Why cannot I resolve keyed registrations from lifetime scope?
问题
我正在尝试从生命周期范围解析带键的服务。以下代码呈现了问题:
public class Service1 : IService1 { }
public interface IService1 { }
public class Service2 : IService2
{
public Service2([KeyFilter("Test")] IService1 service1) { }
}
public class IService2 { }
public static class Program
{
public static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Service1>().Named<IService1>("Test");
builder.RegisterType<Service2>().As<IService2>();
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var service2 = scope.Resolve<IService2>();
}
}
}
我的意图是为特定的其他服务创建多个Service1
注册。我需要使用范围,因为我已将DbContext注册为范围,服务需要它才能正常工作。
在启动演示代码后,我遇到了异常:
Autofac.Core.DependencyResolutionException: '在激活 ManagedConsoleSketchbook.Service2 时抛出了异常。'
内部异常
DependencyResolutionException: 无法使用可用的服务和参数调用类型 'ManagedConsoleSketchbook.Service2' 上找到的任何构造函数:
无法解析参数 'ManagedConsoleSketchbook.IService1 service1' 的构造函数 'Void .ctor(ManagedConsoleSketchbook.IService1)'。
我做错了什么吗?为什么无法从生命周期范围中解析具有名称/键的服务?
英文:
I'm trying to resolve keyed service from a lifetime scope. The following code presents the issue:
public class Service1 : IService1 { }
public interface IService1 { }
public class Service2 : IService2
{
public Service2([KeyFilter("Test")] IService1 service1) { }
}
public class IService2 { }
public static class Program
{
public static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Service1>().Named<IService1>("Test");
builder.RegisterType<Service2>().As<IService2>();
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var service2 = scope.Resolve<IService2>();
}
}
}
My intention is to create multiple Service1
s registrations per specific other services. I need scopes, because I have registered DbContext as scoped and services needs it to work properly.
After starting the demo code, I'm getting the exception:
Autofac.Core.DepencencyResolutionException: 'An exception was thrown while activating ManagedConsoleSketchbook.Service2.'
Inner Exception
DependencyResolutionException: None of the constructors found on type 'ManagedConsoleSketchbook.Service2' can be invoked with the available services and parameters:
Cannot resolve parameter 'ManagedConsoleSketchbook.IService1 service1' of constructor 'Void .ctor(ManagedConsoleSketchbook.IService1)'.
Am I doing something wrong? Why cannot I resolve named/keyed service from a lifetime scope?
答案1
得分: 1
如果您阅读了 KeyFilterAttribute
上的文档,您会注意到您忘记将 .WithAttributeFiltering()
添加到 Service2
的注册中。属性过滤会影响性能,因此它是选择性的。
英文:
If you read the docs on the KeyFilterAttribute
you'll notice you forgot to add .WithAttributeFiltering()
to the Service2
registration. Attribute filtering is a perf hit so it's opt-in.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论