简体   繁体   English

Autofac委托工厂和RegisterGeneratedFactory()的区别

[英]the difference of Autofac delegate factory and RegisterGeneratedFactory()

Accordding to autofac doc , when a service constructor has duplicate types like the following:根据autofac doc ,当服务构造函数具有如下重复类型时:

public class DuplicateTypes
{
  public DuplicateTypes(int a, int b, string c)
  {
    // ...
  }
}

Func<X,Y,B> will not work, you should use a custom delegate type instead: Func<X,Y,B> 不起作用,您应该改用自定义委托类型:

public delegate DuplicateTypes FactoryDelegate(int a, int b, string c);

with the delegate factory,we can resolve the FactoryDelegate without registering anything else:使用委托工厂,我们可以在不注册任何其他内容的情况下解析 FactoryDelegate:

builder.RegisterType<DuplicateTypes>();
var container = builder.Build();
var scope = container.BeginLifetimeScope();
var func = scope.Resolve<FactoryDelegate>();

But in the autofac doc,we can register that delegate using RegisterGeneratedFactory():但是在 autofac 文档中,我们可以使用 RegisterGeneratedFactory() 注册该委托:

builder.RegisterType<DuplicateTypes>();
builder.RegisterGeneratedFactory<FactoryDelegate>(new TypedService(typeof(DuplicateTypes)));

after that we can also resolve the FactoryDelegate.之后我们也可以解析FactoryDelegate。

var func = scope.Resolve<FactoryDelegate>();

So what's the difference of delgate factory and RegisterGeneratedFactory?那么delgate工厂和RegisterGeneratedFactory有什么区别呢? Is RegisterGeneratedFactory redundant? RegisterGeneratedFactory 是多余的吗? If not, which case suites RegisterGeneratedFactory?如果不是,RegisterGeneratedFactory 适合哪种情况?

The short version is you really don't need RegisterGeneratedFactory ever.简短的版本是你真的不需要RegisterGeneratedFactory If you look at the API docs on it , you can see it says:如果您查看API 文档,您会看到它说:

These features are in this namespace because they will remain accessible to applications originally written against Autofac 1.4.这些功能位于此命名空间中,因为它们仍可供最初针对 Autofac 1.4 编写的应用程序访问。 In Autofac 2, this functionality is implicitly provided and thus making explicit registrations is rarely necessary.在 Autofac 2 中,此功能是隐式提供的,因此很少需要进行显式注册。

So, basically, it's there for people who were using it before so we don't break them, but we're into Autofac 6 now and there's no value in using it in new applications.所以,基本上,它是为以前使用它的人准备的,所以我们不会破坏它们,但我们现在进入 Autofac 6,在新应用程序中使用它没有任何价值。

We should probably look at deprecating those methods in Autofac so we can remove them in the next major release or so and reduce confusion.我们可能应该考虑在 Autofac 中弃用这些方法,以便我们可以在下一个主要版本中删除它们并减少混淆。

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

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