1

How can i inject using annotation which is like a feature of Spring MVC

public class AccountController :Controller
{

[Injected] // Need like this annotation
private AccountService _accountService;

public AccountController(){

}

}

2 Answers 2

1

You may use Unity Container

Here is an example:

public class MyObject
{
  private SomeOtherObject _dependentObject;

  [Dependency]
  public SomeOtherObject DependentObject 
  {
    get { return _dependentObject; }
    set { _dependentObject = value; }
  }
} 

And here is the resolution:

IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve<MyObject>();

// now access the property containing the dependency
SomeOtherObject depObj = myInstance.DependentObject;
3
  • dotnet core has its own DI, so using that is better. Nov 30, 2017 at 6:11
  • 1
    @inthevortex "using that is better" ... is not true. It depends on your requirements. Default mechanisme has for example no property injection or there are di frameworks with have better performance on runtime or on startup.
    – Stephu
    Nov 30, 2017 at 7:01
  • @Tester true, if requirements aren't met by it then there are frameworks for it. Nov 30, 2017 at 7:29
1

In .Net core application no need to mention as injected annotation.you need to change your service as interface driven.

In solution startup page add below shown code before services.AddMvc();

        services.AddTransient<IInterface, Service>();

and in controller make change as

public class AccountController :Controller
{ 
   private IAccountService _accountService;
   public AccountController(IAccountService accountService){
       _accountService = accountService;
   }
}
2
  • Hi @Saneesh what are the pros and cons of ASP DI/IoC vs the way that Java Spring/Java EE handle it? I am just starting to explore dot net eco. Jan 20, 2019 at 16:58
  • 1
    Hi asp.net core IoC mainly designed and dedicated for prevent memory leakage, mock testing and thread safe. But with respect to 3 types of Ioc scope it's feature application need to design and develop to get full advantage.. Jan 20, 2019 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.