使用具有 Dependency 关键字和 UnityContainer 的属性进行初始化
我有一个代码示例,看起来像这样。
public class AdventureWorksRepository
{
[Dependency]
private AdventureWorksEntities Context
{
get; set;
}
public AdventureWorksRepository()
{
SelectDemo();
}
public void SelectDemo()
{
var productNames = Context.Products.Select(item => item.Name);
foreach (var productName in productNames)
{
Console.WriteLine("Name : "productName);
}
}
}
这是我所理解的主程序,
private static void Main(string[] args)
{
UnityProvider.Container = new UnityContainer();
UnityProvider.Container.RegisterInstance<AdventureWorksEntities>(new AdventureWorksEntities());
var repository = UnityProvider.Container.Resolve<AdventureWorksRepository>();
}
Dependency 关键字应该告诉 Unity 初始化 AdventureworksEntities 属性,但我不断收到 null 引用异常任何提示我正在做什么或假设错误
I have a code sample which look something like this.
public class AdventureWorksRepository
{
[Dependency]
private AdventureWorksEntities Context
{
get; set;
}
public AdventureWorksRepository()
{
SelectDemo();
}
public void SelectDemo()
{
var productNames = Context.Products.Select(item => item.Name);
foreach (var productName in productNames)
{
Console.WriteLine("Name : "productName);
}
}
}
and heres the main programe
private static void Main(string[] args)
{
UnityProvider.Container = new UnityContainer();
UnityProvider.Container.RegisterInstance<AdventureWorksEntities>(new AdventureWorksEntities());
var repository = UnityProvider.Container.Resolve<AdventureWorksRepository>();
}
from what i've understood the Dependency keyword should tell Unity to initialize the the AdventureworksEntities property but I keep getting and null refrence exception any tips what I'm doing or assuming wrong
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您不要使用
[Dependency]
属性。有了它们,您就可以在代码库中的任何地方引用容器。有关详细说明,请参阅本文。您可以告诉 Unity 您想要使用
InjectionProperty
注入依赖项,如下所示。如果您想将特定值注入该属性而不是让 Unity 解析该值,您还可以在 InjectionProperty 的构造函数中指定您自己的值。
顺便说一句:您的财产必须是公共的。它不适用于私人财产。如果您不想公开该属性,则应该进行构造函数注入
I would recommend that you don't use the
[Dependency]
attribute. With them you have references to your container everywhere in your codebase. See this article for detailed explanation.You can tell Unity that you want a dependency injected using
InjectionProperty
like thisinstead. If you want to inject a specific value into that property instead of letting Unity resolve that value you can also specify your own value in the constructor of InjectionProperty.
Btw.: Your property must be public. It won't work on private properties. If you don't want to make that property public you should instead go for constructor injection