folks, I am learning Asp.net core. I faced with a choice that how to create instance of service type. There are some code that I used to write while using WCF:
public class SomeService:ISomeService
{
[WebInvoke(UriTemplate="action1")]
public void DoSomething1() => new DBAccessBroker1().DoSomethingWithDB();
[WebInvoke(UriTemplate="action2")]
public void DoSomething2() => new DBAccessBroker2().DoSomethingWithDB();
}
In the above code I create the instance of DBAccessBroker while creating service instance SomeService. Now, in the Asp.net Core, the same funtionality can be implemented using Dependency Injection like this:
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<DBAccessBroker1>();
services.AddSingleton<DBAccessBroker2>();
...
}
...
}
public class SomeController : Controller
{
DBAccessBroker1 broker1=null;
DBAccessBroker2 broker2=null;
public SimeController(DBAccessBroker1 broker1,DBAccessBroker2 broker2)
{
this.broker1=broker1;
this.broker2=broker2;
}
[HttpPost("action1")]
public void DoSomething1()=>broker1.DoSomethingWithDB();
[HttpPost("action2")]
public void DoSomething2()=>broker2.DoSomethingWithDB();
}
Obviously, it's more succinct to create instance manually than using DI because there is no need to register DI service and write an odd controller constructor with parameters as if coming from the air.
On the other hand, I believe that there must be benefits to let Microsoft incorporating DI into Asp.Net Core. I guess that DI should be implemented with features like cache or kind of reusable mechanism. But I failed to find some documents to confirm it. So I was wondering if some inside men or people with deeper understanding could tell me the underlying principle of DI. I need be convinced to create instance of my service type using DI rather than manually in my case.
Using DI have at least two pros in your case:
1) You should not care about parameters you should pass to broker constroctors. You will receive ready-to-use instances, while it's creation logic is located in some other place (Startup.cs or custom factory).
2) DI can give you same broker instance to controller and some other services during processing same user request, and give other instance to several classes processing other request (even simultaneously) - if you register them with Scope lifetime.
If you don't need any of this "features" - you may create brokers "manually".