3

I am using Unity for dependency injection in ASP.NET C#.

Normally I would inject dependencies in the constructor, like:

class MyClass
{
   private readonly ISomething _something;

   public MyClass(ISomething something)
   {
      _something = something;
   }

   public MyMethod()
   {
      // _something is instantiated as expected
   }
}

where the dependency has been configured as:

container.RegisterType<ISomething, Something>();

That's all great.

But now I need to do an injection without the use a constructor. So I read that I can use the dependency attribute [Dependency] for this purpose.

class MyClass
{
   [Dependency]
   private ISomething _something { get; set; }

   public MyMethod()
   {
      // _something appears to be null
   }
}

But for some reason _something appears to be null.

What am I missing?

SOLUTION:

See the accepted answer over here, which shows how to create a factory to generate the injected instance:

How to resolve dependency in static class with Unity?

Worked for me!

brinch
  • 2,544
  • 7
  • 33
  • 55

1 Answers1

3

You are trying to inject into a private property. This is not possible.

And personally, I suggest you stick to constructor injections to prevent locking yourself into a specific Dependency Injection framework.

Bastiaan Linders
  • 1,861
  • 2
  • 13
  • 15
  • I updated the question with a solution. So it is indeed possible to do - and it worked well for me. – brinch Sep 13 '17 at 13:50