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
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
InjectionPropertylike 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