Autofac不会将相同实例传递给构造函数中的已解析参数 [英] Autofac not passing same instance to resolved arguments in constructor

查看:119
本文介绍了Autofac不会将相同实例传递给构造函数中的已解析参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下设置

public class CommonClass : ICommonClass
{
}

public class SomeClass : ISomeClass
{
   public SomeClass(ICommonClass common, IOtherClass otherClass) {}
}

public class OtherClass : IOtherClass
{
  public OtherClass(ICommonClass common) {}
}

//Registration
builder.RegisterType<CommonClass>().As<ICommonClass>().InstancePerDependency();
builder.RegisterType<SomeClass>().As<ISomeClass>().InstancePerDependency();
builder.RegisterType<OtherClass>().As<IOtherClass>().InstancePerDependency();

我希望每个构造函数中的公共参数都是相同的实例,但是当SomeClass被解析时,它会创建ICommon的新实例.我怎么能得到这个时间发生.我试图将它们注册为InstancePerLifetimeScope,但其行为与SingleInstance相同.

I would like the common argument in each constructor to be the same instance, but for it to create new instance of ICommon when SomeClass is resolved. How can I get this time happen. I attempted to register them as InstancePerLifetimeScope but it acted the same as SingleInstance.

推荐答案

InstancePerDependency是在每个依赖项都需要新实例时的解决方法.现在,对于不同的依赖类具有不同的生存期是一件棘手的事情,而且感觉不对.如果您可以详细说明为什么需要这种行为,那么可能会找到更好的方法.

InstancePerDependency is the way to go when you need new instances for every dependency. Now to have varying lifetimes for different dependent classes is tricky and doesn't feel right. If you can elaborate on why you need this behavior perhaps a better way could be found.

也就是说,要完成您的要求(尽管我不喜欢它;),您可以使用实例持有人".我的想法是,对于常规依赖项,将照常提供新的公共实例.但是对于特殊情况SomeClass,可以从始终提供相同实例的该Holder类中获取公共实例:

That said, to accomplish what you ask (though I do not like it ;), you could utilize a "instance holder". My thought is that for regular dependencies, new common instances will be served as usual. But for the special case SomeClass, the common instance is fetched from this holder class that always serves the same instance:

public class CommonHolder
{
    public ICommonClass Instance {get;private set;}
    public CommonHolder(ICommonClass commonInstance)
    {
        Instance = commonInstance;
    }
}

然后进行注册设置:

builder.RegisterType<CommonHolder>().SingleInstance();
builder.RegisterType<OtherClass>().As<IOtherClass>().InstancePerDependency();
builder.RegisterType<CommonClass>().As<ICommonClass>().InstancePerDependency();

builder.RegisterType<SomeClass>().InstancePerDependency();
builder.Register(c =>
    c.Resolve<SomeClass>(TypedParameter.From(c.Resolve<CommonHolder>().Instance)))
    .As<ISomeClass>().InstancePerDependency();

这篇关于Autofac不会将相同实例传递给构造函数中的已解析参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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