使用autofac创建需要参数的对象的正确方法是什么?

编程入门 行业动态 更新时间:2024-10-26 22:28:02
本文介绍了使用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创建需要参数的对象的正确方法是什么?

本文发布于:2023-11-05 21:16:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   正确   参数   方法   autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!