简体   繁体   中英

DryIoc - ASP.Net Core - Scope context per request

I want to use DryIoc in my application (ASP.Net Core 2.2). I want to use the same instance of services during execution of the call of one API service. (During Http call / scoped context). If it was in ASP.Net WebApi, I would like to have a scope per http context. In the DryIoc documentation, it is possible to use AsyncExecutionFlowScopeContext for WebApi.

But, with ASP.Net Core, I don't really understand how to use and declare a scope per request.

My code is based on this sample: https://github.com/dadhi/DryIoc/tree/master/samples/DryIoc.AspNetCore.Sample

If I tried to resolve a service declared as ScopeService (Reuse.Scoped) I have the issue : Unable to resolve IScopedService IsResolutionCall from Container without Scope.

For your information, the declaration of my container is like in the sample:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc()

    // Enables controllers to be resolved by DryIoc, OTHERWISE resolved by infrastructure
    .AddControllersAsServices();

    var container = new Container(rules => rules.With(
        propertiesAndFields: request => 
        request.ServiceType.Name.EndsWith("Controller")
        ? PropertiesAndFields.Properties()(request)
        : null)
        .WithCaptureContainerDisposeStackTrace());

    Container = container;

    return container.WithDependencyInjectionAdapter(services,
        throwIfUnresolved: type => type.Name.EndsWith("Controller"))
        // Your registrations are defined in CompositionRoot class
        .ConfigureServiceProvider<CompositionRoot>();
}

For the registration:

public CompositionRoot(IRegistrator r)
{
    r.Register<ISingletonService, SingletonService>(Reuse.Singleton);
    r.Register<ITransientService, TransientService>(Reuse.Transient);
    r.Register<IScopedService, ScopedService>(Reuse.Scoped);
 }

And if I try to do this in one service:

var myScopedServvie = Container.Resolve<IScopedService>();

I have the exception: ContainerException: Unable to resolve IScopedService IsResolutionCall from Container without Scope with Rules with {CaptureContainerDisposeStackTrace} with Made={PropertiesAndFields=}

So my question: how can I open a scope for each request of my API? I can see some tests where there is:

(var scope = container.OpenScope())
...

But I don't know how to use this code in my application.

Thanks for your help.

A scope will be automatically open per each web request by Asp .Net Core framework, you don't need to bother.

If you want to test the container setup, then you may OpenScope manually in the respective test, and resolve from the returned scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM