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!

1
  • "But now I need to do an injection without the use a constructor." Why do you need this? Commented Dec 30, 2016 at 8:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I updated the question with a solution. So it is indeed possible to do - and it worked well for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.