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

时间:2018-09-07 14:36:31

标签: c# dependency-injection autofac

我想使用带参数的构造函数来注册两个依赖项,但是我只想一次在“ Dependency”类中创建“ new”。 代替这个:

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

我想要这样的东西:

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

2 个答案:

答案 0 :(得分:2)

假设有一个原因要实例化类型而不是向Autofac注册该类型,那么您应该使用Register而不是RegisterInstance

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

然后,您可以使用传入的IComponentContext来解决所有必需的依赖项。请记住,在SingleInstance中,您的实例仅创建一次,因此依赖项的作用域应类似(不要期望每个请求的依赖项在每次调用您的单例时都会“更新”自身)。

答案 1 :(得分:2)

如果您先注册依赖项,则在需要时,应该自动将其传递给新实例。

假设:

  File "/home/igorsavinkin555/corrections-msword/main.py", line 2, in <module>
    from docx.document import Document
  File "/home/igorsavinkin555/corrections-msword/lib/docx/__init__.py", line 3, in <module>
    from docx.api import Document  # noqa
  File "/home/igorsavinkin555/corrections-msword/lib/docx/api.py", line 14, in <module>
    from docx.package import Package
  File "/home/igorsavinkin555/corrections-msword/lib/docx/package.py", line 11, in <module>
    from docx.opc.package import OpcPackage
  File "/home/igorsavinkin555/corrections-msword/lib/docx/opc/package.py", line 12, in <module>
    from .part import PartFactory
  File "/home/igorsavinkin555/corrections-msword/lib/docx/opc/part.py", line 12, in <module>
    from .oxml import serialize_part_xml
  File "/home/igorsavinkin555/corrections-msword/lib/docx/opc/oxml.py", line 12, in <module>
    from lxml import etree
  File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/sandbox.py
", line 1095, in load_module
    raise ImportError('No module named %s' % fullname)
ImportError: No module named lxml.etree

然后注册依赖项

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

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