0
votes

Trying to implement autofac with my WebApi ... but having some issues with lifetime for my objects...

My startup webapi class:

var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();

    container.RegisterType<MyConcreteClass>().As<IMyInterface>().InstancePerRequest();

    var container = builder.Build();

    app.UseAutofacMiddleware(container);
    app.UseAutofacWebApi(config);


    var csl = new AutofacServiceLocator(container);
    ServiceLocator.SetLocatorProvider(() => csl);


    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

But not works

Unable to resolve the type 'IMyInterface' because the lifetime scope it belongs in can't be located. The following services are exposed by this registration: - IMyInterface

Details ---> No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.

If you see this during execution of a web application, it generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario). Under the web integration always request dependencies from the dependency resolver or the request lifetime scope, never from the container itself. (See inner exception for details.)

Removing this part .InstancePerRequest(); , then works, but the object is not disposing.

What am i doing wrong ?

Thanks!

1

1 Answers

1
votes

I strongly suspect the problem lies with the following code:

var csl = new AutofacServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => csl);

The error message indicates you must resolve dependencies using the dependency resolver, but this is bypassing that and using the container itself.

On a side note, using a service locator is anti-pattern. You should be injecting dependencies into your controllers and other MVC extension points rather than using this approach.