Reputation: 2614
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!
Upvotes: 3
Views: 10686
Reputation: 2141
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.
Upvotes: 3