使用Autofac将参数传递给构造函数

使用Autofac将参数传递给构造函数

本文介绍了使用Autofac将参数传递给构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对autofac还是很陌生,所以有可能我完全滥用了它.

I'm very new to autofac so it's possible that I'm completely misusing it.

假设我有一个具有以下结构的类:

Let's say I have a class that has this structure:

public class HelperClass : IHelperClass
{
     public HelperClass(string a, string b)
     {
         this.A = a;
         this.B = b;
     }
}

,我有两个使用该类的类,但是对于构造函数需要不同的默认值.第二个构造函数只是出于测试目的-我们将始终在真实"应用程序中使用HelperClass.

and I have two classes that use that class, but require different defaults for the constructor. The second constructor is JUST for testing purposes -- we will always want a HelperClass in the "real" app.:

public class DoesSomething: IDoesSomething
{
     public DoesSomething()
         : this(new HelperClass("do", "something"));
     {

     }

     internal DoesSomething(IHelperClass helper)
     {
          this.Helper = helper;
     }
}

public class DoesSomethingElse : IDoesSomethingElse
{
     public DoesSomethingElse()
         : this(new HelperClass("does", "somethingelse"));
     {

     }

     internal DoesSomethingElse(IHelperClass helper)
     {
          this.Helper = helper;
     }
}

这是我的AutoFac模块:

Here's my AutoFac module:

public class SomethingModule: Module
{
    protected override void Load(ContainerBuilder builder)
    {
         builder.RegisterType<DoesSomething>().As<IDoesSomething>();
         builder.RegisterType<DoesSomethingElse>().As<IDoesSomethingElse();
    }
}

我的问题:

  1. 当我在DoesSomething或DoesSomethignElse上调用resolve时,它将解析内部构造函数而不是公共构造函数吗?我需要保留IHelperClass的未注册状态吗?
  2. 如果是,我如何使它传递不同的参数到IHelperClass的每个实例,具体取决于它是在DidSomething还是DidSomethingElse中使用的?

推荐答案

Autofac不使用非公共构造函数.默认情况下,它仅查找公共对象,而根本看不到其他对象.除非您使用.FindConstructorsWith(BindingFlags.NonPublic),否则它将仅看到公共构造函数.因此,您的方案应该可以按预期工作.

Autofac does not use non-public constructors. By default, it only finds public ones and simply doesn't see the others. Unless you use .FindConstructorsWith(BindingFlags.NonPublic), it will see only public constructors. Therefore your scenario should work as you expect it to do.

这篇关于使用Autofac将参数传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 11:12