Search code examples
c#inversion-of-controlcastle-windsoraspnetboilerplate

"Globally" resolving service causes no more property injection


In my asp boilerplate for mvc project called "Ks"

Calls for webapi, ioc resolve KsSession to relevant instance of derived class as noted here

But the issue starts when I tried to resolve the a service called MobileUserService without injection but "globally" as shown below. From the second call KsSession does not resolve any more. It happens property set calls from constructor to NullKsSession but no more property injection.

In Global.asax :

protected override void Application_BeginRequest(object sender, EventArgs e)
{
    base.Application_BeginRequest(sender, e);
    var service = Ks.Dependency.IocManager.Instance.Resolve<Service.MobileUser.IMobileUserService>();
}

My question is why this happening, isn't it appropriate use service such way?

Note I have added huge details in github issue but here is concise version of what is happening.


Solution

  • Looks like you apply a bad practise. I'd register IMobileUserServie as singleton. And resolve it formally. Anyway for your question, try to create a new scope and resolve your interface in your custom scope. Altough I don't recommend this, you can use the below code

    protected override void Application_BeginRequest(object sender, EventArgs e)
    {
        base.Application_BeginRequest(sender, e);
        var iocResolver = Ks.Dependency.IocManager.Instance.Resolve<IIocResolver>();
        var scope = iocResolver.CreateScope();
        var service = scope.Resolve<Service.MobileUser.IMobileUserService>();
    }