在autofac容器解析之前必须注册每个类吗? [英] Have to register every class before the autofac container can resolve?
问题描述
让我们说这种情况:
public class B {};
public class C
{
public C(B b){}
}
要从Autofac容器解析C,我必须将B和C都注册到容器. 但是,今天我使用了 Unity ,看来我只需要在容器中注册B,然后C就可以解决.
To resolve C from Autofac container, I have to register both B and C to container. But, today I used Unity, it seems I just need to register B to container, then C can be resolved.
那么Autofac不能像Unity一样吗?
So Autofac can't do as Unity do?
推荐答案
使用现成的Autofac,可以直接在Register...
方法中将要使用的每种类型都注册到容器中或使用RegisterAssemblyTypes
批量下载.但是也有其他选择,请参阅尼古拉斯有关解决所有问题的文章.所以是的,Autofac可以完成Unity的工作,但是您必须启用它.
With out-of-the-box Autofac it is expected that every type you want to use is registered with the container, either directly using the Register...
methods or in bulk using RegisterAssemblyTypes
. But there are other options too, take a look at Nicholas article about resolving everything. So yes, Autofac can do what Unity does, but you'll have to enable it.
更新:实际上,解决任何问题"功能现已内置,您可以执行以下操作:
Update: actually, the "resolve anything" feature is built-in now, and you can do the following:
var cb = new ContainerBuilder();
cb.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
return cb.Build();
使用AnyConcreteTypeNotAlreadyRegisteredSource
,您实际上可以解析C
和B
,而无需注册它们中的任何一个.
With the AnyConcreteTypeNotAlreadyRegisteredSource
you can actually resolve both C
and B
without registering any of them.
请注意,由AnyConcreteTypeNotAlreadyRegisteredSource
解析的服务的生命周期将为每个依赖关系范围" .
Note that the lifetime of services resolved by AnyConcreteTypeNotAlreadyRegisteredSource
will be "per dependency scope".
注意:本主题 Autofac讨论组中的结束与此相关.
Note: this topic over at the Autofac discussion group is related.
这篇关于在autofac容器解析之前必须注册每个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!