Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject instance with [Dependency] attribute using Unity?

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!

like image 288
brinch Avatar asked Mar 01 '26 14:03

brinch


1 Answers

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.

like image 135
Bastiaan Linders Avatar answered Mar 03 '26 04:03

Bastiaan Linders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!