MVC 3 ninject bind lazy evaluated parameter
-
27-10-2019 - |
Question
I want o bind my controller with a parameter that is lazy evaluated.
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
return controllerType == null
? null
: (IController) _ninjectKernel.Get(controllerType);
}
catch (Exception ex)
{
throw;
}
}
And I have the next binding:
_ninjectKernel.Bind<IFilesRepository>().To<FilesManager>().WithConstructorArgument("storageFolderAbsolutePath", c => c.ToString());
The problem is at the lambda function. I want to return Server.MapPath("/") ... but I don't have the request context in the c object. How can I sent it?
Solution
I'm not overly familiar with Ninject, but you should be able to register a provider with the container to be able to resolve a HttpContextBase
. By doing so, the IFilesRepository
can now take a HttpContextBase
as a constructor argument, which will be injected by the container, using the provider, when creating an instance of IFilesRepository
.
To register a provider (using a delegate to resolve the service),
Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current));
Be aware however, that the life style of an IFilesRepository
would most likely need to change to a "per Web Request" lifestyle, as the HttpContext.Current
is created per web request, so you wouldn't want to go holding onto that in an IFilesRepository
that had a longer life style. You may want to abstract out the "mapping paths" functionality so that you can have an IFilesRepository
with a longer lifestyle.
OTHER TIPS
Since the server variable is related to the current HttpContext you will have to retrieve it inside the FilesManager class (using a separate Interface for that purpose if you will )