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 InjectionProperty like this
container.RegisterType(typeof(IMyInterface), typeof(MyImplementation), new InjectionProperty("MyProperty"));
instead. 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
public class AdventureWorksRepository
{
private readonly AdventureWorksContext context;
public AdventureWorksRepository(AdventureWorksContext context)
{
if(context == null) throw new ArgumentNullException("context");
this.context = context;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With