I am using ASP.Net Core Dependency Injection in an MVC App (not .Net Core app, but classic ASP.NET MVC Applicatio) I am using DI by adding the Microsoft.Extensions.DependencyInjection Nuget package. I am trying to create scoped life time for my controllers so I have a new scope whenever I create my controllers but I am getting the same instance always for my requests and there is an error as below "A single instance of controller 'X.Controllers.HomeController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request"
I have used a custom factory to create my controllers and used new scope to create the controllers . and the scope is disposed in the ReleaseController method
public class MyServiceFactory : DefaultControllerFactory
{
private readonly IServiceContainer _dependencyManager;
public MyServiceFactory (IServiceContainer dependencyManager)
{
this._dependencyManager = dependencyManager;
}
public override void ReleaseController(IController controller)
{
_dependencyManager.Release(((ServiceEndPoint)controller).Context.RuntimeContext.Scope);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
}
var scope = _dependencyManager.GetNewScope();
var service=(ServiceEndPoint)_dependencyManager.Resolve(scope, controllerType);
service.Context.RuntimeContext.SetScope(scope);
return service;
}
}
The ServiceEndpoint is just a base class derived from Controller and I am using it as the base for all my controllers which contains some common logic. I am setting a Context for my controllers which also contain the newly created scope and I am disposing my scope in Releasecontroller by getting it from the Context. _dependencyManager.GetNewScope() create a New scope as below
return _container.CreateScope();
where _container is an Instance of IServiceProvider
The code _dependencyManager.Resolve(scope, type) is as below
public object Resolve(IServiceScope scope,Type type)
{
return scope.ServiceProvider.GetService(type);
}