I've got a MVC WebApi owin (soft hosted) project, that uses Unity for resolving controller dependencies
which look like this
public class PacientaiController : ODataController
{
private readonly IEntityRepo<Ent.Pacientas> repo;
public PacientaiController(IEntityRepo<Ent.Pacientas> repo)
{
this.repo = repo;
}
the problem I'm trying to solve - is how do I pass 'OwinContex' into a Repo.
public class PacientasEntityRepo:IEntityRepo<Pacientas>,IDisposable
{
public PacientasEntityRepo(IOwinContext ctx)
{
.........
If I try to register it like this in the Startup.cs
Container.RegisterType<IOwinContext>(new InjectionFactory(o => HttpContext.Current.GetOwinContext()));
I get a null ref, saying that HttpContext.Current
is NULL
The main idea here, is to pass the currently authenticated user to the repo, because Repo host the Logic for querying the Database, depending on the user. (say if the user is Admin, then return this data, if the user is guest - return this data)
The point being - that this is a self Host !
Lets put aside why you have this design and concentrate to the problem: injecting the
IOwinContext
:you can also get it from a
HttpRequestMessage
instance with theGetOwinContext
method, however you also need to get aHttpRequestMessage
somehow.Unity does not support injection of the
HttpRequestMessage
out of the box but you can use a customDelegatingHandler
which stores the currentHttpRequestMessage
in the container as described here: Inject WebAPI UrlHelper into service using AutofacThe linked question is about Autofac but you can transfer it for work with Unity:
The
CurrentRequest
and theCurrentRequestHandler
can be used from Andrew Davey's answer as it is:Then you just need to register the
DelegatingHandler
with:And register the
CurrentRequest
andIOwinContext
in the containerBeside the custom delegation handler there are other places to hook into Web.API to capture the
HttpRequestMessage
for example you can create your ownIHttpControllerActivator
and use theExecuteAsync
method as described here: Dependency Injection in ASP.NET Web API 2In a selfhosted application you do not have a HttpContext. You need an other way to move the state around. An option is to use a self implemented HttpContext like:
https://github.com/danielcrenna/graveyard/tree/master/httpcontext-shim
I think the problem is that HttpContext does not exist at the time Startup is called, so what you probably need, is to have a Func instead, like this:
and then change the code in Startup to this: