Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing using properties with Dependency keyword and UnityContainer

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

like image 332
Arshad Badar Khan Avatar asked Jun 25 '26 06:06

Arshad Badar Khan


1 Answers

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;
  }
}
like image 54
Sebastian Weber Avatar answered Jun 26 '26 19:06

Sebastian Weber