我有一个代码示例,看起来像这样。
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 refrence 异常任何提示我在做什么或假设错误
最佳答案
我建议您不要使用 [Dependency]
属性。有了它们,您就可以在代码库的任何地方引用您的容器。参见 this article详细解释。
您可以像这样使用 InjectionProperty
告诉 Unity 您想要注入(inject)依赖项
container.RegisterType(typeof(IMyInterface), typeof(MyImplementation), new InjectionProperty("MyProperty"));
相反。如果您想将特定值注入(inject)该属性而不是让 Unity 解析该值,您还可以在 InjectionProperty 的构造函数中指定您自己的值。
顺便说一句:您的属性(property)必须是公开的。它不适用于私有(private)属性(property)。如果您不想公开该属性,则应该转而进行构造函数注入(inject)
public class AdventureWorksRepository
{
private readonly AdventureWorksContext context;
public AdventureWorksRepository(AdventureWorksContext context)
{
if(context == null) throw new ArgumentNullException("context");
this.context = context;
}
}
关于c# - 使用带有 Dependency 关键字和 UnityContainer 的属性进行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8982297/