I recently wrote a blog post about sharing Dependency resolvers between MVC and Web API, but I got excited to see this article from MSDN today. I’m a huge proponent of Dependency Injection to decouple service and the pluggable architecture it brings, so I’m glad to see if taking a front row seat in the upcoming .NET framework.
The article cites a handful of the types of instances it creates: singleton, scoped, transient, and “DIY” (instance) and their corresponding methods of creation (uncommented below for demonstrations purposes only). The linked article talks about these types of instances in greater detail.
namespace WebDemo
{
public class Startup
{
public void Configure(IBuilder app)
{
app.UseServices(services =>
{
// Instance
services.AddInstance<IRepository>(new DataRepository { Data = "Initialized from global" });
// Transient
services.AddTransient<IRepository, DataRepository>();
// Singleton
services.AddSingleton<IRepository, DataRepository>();
// Scoped
services.AddScoped<IRepository, DataRepository>();
});
}
}
}
And without any other configuration, aside from the omitted/unrelated configuration for enabling MVC in the Katana Startup class, we magically have a constructor-injected instance!
Leave a Reply