I have read all those articles but still struggle to find the 'correct' way to implement Dependency Injection into the CMS. This is because we have one solution (and shared projects) which expose services and the necessary di registrations for both CMS & MVC like so:
// file: MyProject.Business.ServiceCollectionExtensions
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddMyBusiness(this IServiceCollection services)
{
services.AddScoped<IMyBusiness, MyBusiness>();
}
}
}
This way we can do in the CMS as well in our MVC hosting site the following:
services.AddMyBusiness();
So we 'must' support scoped
services too to.
In our application start of the CMS we then do this:
MyBusiness.Common.ServiceLocator.ResolverFunction = (type) =>
{
if (HttpContext.Current == null)
{
using (var scope = _serviceProvider.CreateScope())
{
return scope.ServiceProvider.GetService(type);
}
}
else
{
return _serviceProvider.GetService(type);
}
}
This creates a new scope for every requested service, so results practically in transient resolutions.
The other option would be to create a scope everytime I want to request services, something like this:
public class MyScheduledTask : ITask
{
public string Execute(TaskInfo task)
{
var serviceProvider = MyBusiness.Common.ServiceLocator.Resolve<IServiceProvider>();
using (var scope = serviceProvider.CreateScope())
{
var myService = scope.ServiceProvider.GetService<IMyService>();
var myOtherService = scope.ServiceProvider.GetService<IMyOtherService>();
}
}
}