简体   繁体   English

在Autofac中注册时如何避免两次使用new

[英]How to avoid using new twice when registering in Autofac

I want to register two dependencies using constructors with parameters but I want only to make 'new' on the 'Dependency' class one time. 我想使用带有参数的构造函数来注册两个依赖项,但是我只想在“ Dependency”类上创建“ new”一次。 Instead of this: 代替这个:

builder.RegisterInstance(new ClassA(new Dependency())).As<IClassA>().SingleInstance();
builder.RegisterInstance(new ClassB(new Dependency())).AsSelf().SingleInstance();

I want something like this: 我想要这样的东西:

Dependency dependency = new Dependency();
builder.RegisterInstance(new ClassA(dependency)).As<IClassA>().SingleInstance();
builder.RegisterInstance(new ClassB(dependency)).AsSelf().SingleInstance();

Assuming that there is a reason you want to instantiate the type instead of registering it with Autofac which will do it for you then you should use Register instead of RegisterInstance . 假设您有理由要实例化类型,而不是使用Autofac进行注册,那么您应该使用Register而不是RegisterInstance

builder.RegisterType<Dependency>().As<Dependency>().SingleInstance();
builder.Register(t => new ClassA(t.Resolve<Dependency>())).As<IClassA>().SingleInstance();

You can then use the passed in IComponentContext to resolve any required dependencies. 然后,您可以使用IComponentContext传递的解析任何必需的依赖项。 Do keep in mind that with SingleInstance your instance is only created once so dependencies should be scoped similarly (don't expect a per request dependency to "renew" itself with every call to your singleton). 请记住,使用SingleInstance您的实例仅创建一次,因此依赖项的作用域应类似(不要期望每个请求的依赖项在每次调用您的Singleton时都会“自我更新”)。

If you register the dependency first it should automatically get passed to the new instances if they require it. 如果先注册依赖项,则在它们需要时应自动将其传递给新实例。

Assumptions: 假设:

public class ClassA : IClassA
{
    public ClassA(Dependency dependency)
    {
    }
 }

public class ClassB
{
    public ClassB(Dependency dependency)
    {
    }
 }

Then register dependency 然后注册依赖

var dependency = new Dependency();
builder.RegisterInstance(dependency).As<Dependency>();
builder.RegisterType<ClassA>().As<IClassA>().SingleInstance();
builder.RegisterType<ClassB>().AsSelf().SingleInstance();

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

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