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.