使用autofac创建需要参数的对象的正确方法是什么? [英] What is the proper way to create objects which require parameters using autofac?
问题描述
我认为我了解了有关依赖倒置和使用IoC容器的大部分信息,但对我来说仍然不清楚.如何使用autofac自动化以下工厂:
I think I get most things about dependency inversion and using an IoC container, but one thing still does not appear clear to me. How do I use autofac to automate the following factory:
public class WidgetFactory
{
public static IWidget Create(int foo, double bar)
{
return new Widget(foo, bar);
}
}
public class Widget
{
private readonly int foo;
private readonly double bar;
public Widget(int foo, double bar)
{
this.foo = foo;
this.bar = bar;
}
}
在其他地方...
public class FoobarUser
{
public void Method()
{
var widget = WidgetFactory.Create(3, 4.863);
// Do something with my widget
// Possibly add it to a widget collection
}
}
基本上,我需要创建成千上万个小部件,但我不确定这样做的最佳方法.考虑到Method不包含对IContainer的引用,我将如何使用autofac创建小部件工厂,以及如何在Method中使用它?
Basically, I need thousands of widgets to be created and I'm not sure of the best way of doing so. How would I create the widget factory using autofac and how would I use that in Method, bearing in mind that Method does not contain a reference to the IContainer?
推荐答案
解决此问题的方法如下:
The way to fix this problem is the following:
更改WidgetFactory以定义用于创建窗口小部件的委托:
Change WidgetFactory to define a delegate for creating widgets:
public class WidgetFactory
{
public delegate IWidget Create(int firstParam, double secondParam);
}
在autofac模块中,使用RegisterGeneratedFactory方法连接工厂.这将自动为您创建工厂:
In your autofac module, wire up the factory using the RegisterGeneratedFactory method. This will automatically create your factory for you:
public class TestClassModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<Widget>().As<IWidget>();
builder.RegisterGeneratedFactory<WidgetFactory.Create>(new TypedService(typeof(IWidget)));
builder.RegisterType<FoobarUser>();
}
}
将工厂注入FoobarUser:
Inject the factory into FoobarUser:
public class FoobarUser
{
private readonly WidgetFactory.Create factory;
public FoobarUser(WidgetFactory.Create factory)
{
this.factory = factory;
}
public void Method()
{
var widget = this.factory(3, 4.836);
// Do something with my widget
// Possibly add it to a widget collection
}
}
这篇关于使用autofac创建需要参数的对象的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!