[英]Resolving a service in autofac without registering service type
Is it possible to resolve a service in autofac without registering it with the container? 是否可以在autofac中解析服务而无需将其注册到容器中?
So far I have come up with something like this: 到目前为止,我已经提出了这样的建议:
public object ResolveUnknownService(IContainer container, Type serviceType)
{
ILifetimeScope lifetimeScope = container.BeginLifetimeScope(b => b.RegisterType(serviceType).ExternallyOwned());
try
{
return lifetimeScope.Resolve(serviceType);
}
finally
{
lifetimeScope.Dispose();
}
}
It works, but I am a bit worried about performance. 它可以工作,但是我有点担心性能。 I also don't want to use AnyConcreteTypeNotAlreadyRegisteredSource beacuse I want to be specific about which services I want (or don't want) to resolve this way.
我也不想使用AnyConcreteTypeNotAlreadyRegisteredSource,因为我想具体说明我想要(或不想)使用哪种服务来解决此问题。
In your example, disposing the temporary lifetime scope will dispose the object being returned as well as any of its dependencies; 在您的示例中,处置临时生存期范围将处置所返回的对象及其任何依赖项。 components only live as long as the lifetime scope that they were resolved from.
组件的生存期仅与解决它们的生存期范围有关。
Are there any known criteria that identifies these types? 是否存在识别这些类型的已知标准? There is an overload of the
AnyConcrete...
class's constructor that can specify a filter on what it will resolve. AnyConcrete...
类的构造函数有很多重载,可以针对要解决的问题指定一个过滤器。 If there are such criteria though then RegisterAssemblyTypes()
is almost always a better option. 如果有这样的条件,那么
RegisterAssemblyTypes()
几乎总是一个更好的选择。
(Unless you're integrating with a legacy/third-party framework then this pattern is probably not the best way to use Autofac, as it leads down the Service Locator path. YMMV of course.) (除非您要与旧版/第三方框架集成,否则此模式可能不是使用Autofac的最佳方法,因为它会导致Service Locator路径失效。当然是YMMV。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.