就像Ninject的[Inject]属性一样,autofac中的等效项是什么?

时间:2019-05-06 07:25:38

标签: c# ninject autofac

我是Autofac的新手。我知道使用Autofac,我需要像下面这样注册这些属性:Property Injection。我正在Autofac中寻找某些东西,就像Ninject中的[Inject]属性一样。 像这样:

[Inject]
public Interface Someproperty { get; set; }

Autofac可以完成类似的事情吗? 任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

Autofac不使用属性。只需公开要注入的属性,并确保它们具有set,其余的由Autofac完成。

var builder = new ContainerBuilder();

// Register the type you want the properties wired up
builder.RegisterType<YourType>().PropertiesAutowired();

// You have to register the thing you want injected to - the value of the property
// and it has to be registered to expose the type of the property. So if the property
// being injected is type `Interface` then make sure you say that here.
builder.RegisterType<AClass>().As<Interface>();

如果您真的要控制通过属性注入哪些属性(我不建议这样做),因为将与DI相关的内容与您的业务逻辑交织在一起不是一种好习惯-there is a working example in the Autofac repo in the form of a unit test。该示例说明如何创建自己的自定义属性,以及如何使用自定义Autofac属性选择器仅连接具有该自定义属性的属性。

相关问题