0

I have legacy Web Forms application with Web Api 2. I installed Autofac to get some little help of DI.

Implemented IContainerProviderAccessor on Global.asax and registered all I need.


/// <summary>
/// Provider that holds the application container.
/// </summary>
static IContainerProvider s_containerProvider;

/// <summary>
/// Instance property that will be used by Autofac HttpModules to resolve and inject dependencies.
/// </summary>
public IContainerProvider ContainerProvider
{
    get { return s_containerProvider; }
}

// Build up your application container and register your dependencies.
var builder = new ContainerBuilder();
AutofacBootstraper.RegisterDependencies(builder);

// Set the dependency resolver to be Autofac.
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

// Once you're done registering things, set the container provider up with your registrations.
s_containerProvider = new ContainerProvider(container);

It works in controllers etc.

But I want to resolve my services in other parts in application. Not just in controllers.

In some classes I was able to use Resolve in pattern

var cpa = ((IContainerProviderAccessor)HttpContext.Current.ApplicationInstance);
var scope = cpa.ContainerProvider.RequestLifetime;
_myFacade = scope.Resolve<IMyFacade>();

So I used HttpContext.

But in other parts I'm using parallel procesing and tasks. For example

public class MyController : ApiControllerBase
{

    public IHttpActionResult DoSomething()
    {
        _myFacade.DoSomething();
        return Ok();
    }
}

public class MyFacade : IMyFacade
{
    public void DoSomething()
    {
        Task.Run(() =>
            {
                DoSomethingInTask()
            }
        )
    }
}

Well, now I want to use the same resolve pattern as before in method DoSomethingInTask, but of course there is no HttpRequest, so is is not possible. Different task, different scope etc.

Is there any way how to get Autofac container and call Resolve<> anywhere? Maybe using GlobalConfiguration.Configuration.DependencyResolver?

Raptor
  • 392
  • 1
  • 4
  • 21

1 Answers1

0

Is there any way how to get Autofac container and call Resolve<> anywhere?

yes.it's in the office doc in the Manual Property Injection section,but you can use the container for resolving.

official doc:https://autofac.readthedocs.io/en/latest/integration/webforms.html#manual-property-injection

var container=(Autofac.Integration.Web.IContainerProviderAccessor) HttpContext.Current.ApplicationInstance;
var myService=container.ContainerProvider.ApplicationContainer.Resolve<IMyService>();
myService.SomeMethod(....)

but of course there is no HttpRequest

yes, but you can get the httpcontext: Using HttpContext in Async Task

phiree
  • 409
  • 6
  • 15