C# 如何将Func用作注入属性
我试图将Func传递给类实例的公共属性。每当我尝试访问该属性时,它都显示为null 自动传真配置:C# 如何将Func用作注入属性,c#,dependency-injection,autofac,C#,Dependency Injection,Autofac,我试图将Func传递给类实例的公共属性。每当我尝试访问该属性时,它都显示为null 自动传真配置: builder.RegisterType<Func<BillingStore>>().PropertiesAutowired(); 公共财产: public static Func<BillingStore> BillingStoreFactory { get; set; } 我看不出我做错了什么,我通常试图避免委托,但这次我不能。在没有static关键字的
builder.RegisterType<Func<BillingStore>>().PropertiesAutowired();
公共财产:
public static Func<BillingStore> BillingStoreFactory { get; set; }
我看不出我做错了什么,我通常试图避免委托,但这次我不能。在没有static关键字的情况下定义属性
public Func<BillingStore> BillingStoreFactory { get; set; }
定义不带static关键字的属性
public Func<BillingStore> BillingStoreFactory { get; set; }
看来这里有很多事情可能会给你带来麻烦 首先,让我们总结一下代码示例,这样我们就有一些东西要谈了。我想你有这样的想法:
void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<Func<BillingStore>>().PropertiesAutowired();
builder.RegisterType<Consumer>();
var container = builder.Build();
var consumer = container.Resolve<Consumer>();
// The BillingStoreFactory property is null here
// but you want it populated.
}
public class BillingStore { }
public class Consumer
{
public static Func<BillingStore> BillingStoreFactory { get; set; }
}
问题2:您在错误的对象上设置属性Autowired。把它放在消费者身上。PropertiesAutowired的要点是,当我解析这个对象时,我希望你也注入它的属性。现在在函数/工厂中有了它,所以Autofac将尝试在Func上注入属性,而不是Func类型的属性。您希望在具有属性的对象上填充属性-消费对象
builder.RegisterType<Consumer>().PropertiesAutowired();
如果我们将其放在一起,更新后的代码如下所示:
我建议在Autofac上阅读和。我们有很多文档和示例可以帮助您解决这个问题。这里似乎有很多事情可能会给您带来麻烦 首先,让我们总结一下代码示例,这样我们就有一些东西要谈了。我想你有这样的想法:
void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<Func<BillingStore>>().PropertiesAutowired();
builder.RegisterType<Consumer>();
var container = builder.Build();
var consumer = container.Resolve<Consumer>();
// The BillingStoreFactory property is null here
// but you want it populated.
}
public class BillingStore { }
public class Consumer
{
public static Func<BillingStore> BillingStoreFactory { get; set; }
}
问题2:您在错误的对象上设置属性Autowired。把它放在消费者身上。PropertiesAutowired的要点是,当我解析这个对象时,我希望你也注入它的属性。现在在函数/工厂中有了它,所以Autofac将尝试在Func上注入属性,而不是Func类型的属性。您希望在具有属性的对象上填充属性-消费对象
builder.RegisterType<Consumer>().PropertiesAutowired();
如果我们将其放在一起,更新后的代码如下所示:
我建议在Autofac上阅读和。我们有很多文档和示例可以帮助您解决这个问题。将Func传递给类实例的公共属性,但该属性定义为公共静态,因此它不是实例属性…将Func传递给类实例的公共属性,但该属性定义为公共静态,所以它不是一个实例属性。。。