必须在 autofac 容器解析之前注册每个类? [英] Have to register every class before the autofac container can resolve?

查看:31
本文介绍了必须在 autofac 容器解析之前注册每个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这个场景:

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,您实际上可以同时解析CB,而无需注册其中任何一个.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆