Autofac: No scope with a matching AutofacWebRequest tag

0

I'd like your help to solve the following problem: Imagine that I have a ServiceFactory class responsible for creating services (as srvFact.Create<MyService>() ), a RepositoryFactory class responsible for creating repositories (as repFact.Create<MeuRepositorio>() ). These classes have dependencies, which I will show by the symbol A <= B , which denotes that A depends on B. For my case I have to: ServiceFactory <= RepositoryFactory .
RepositoryFactory <= DbContext . Having said that, imagine that my api uses Automapper to map ViewModels to Objects of the Entity Framework and that for certain mappings, it is necessary to access some repository. What I want: I would like given a request, while this request lives, any request to an instance of DbContext, return the same instance, to better control the life cycle of DbContext. Let's go to the code snippet:

internal void Configure(ContainerBuilder builder)
{
    ConfigureContainer(builder);
    Container = builder.Build();
    RegisterMapping();
}

private void ConfigureContainer(ContainerBuilder builder)
{
    var dbContextType = GetDbContextType();
    var assembly = GetWebApiAssembly();

    // (a) com essa linha o metodo 'RegisterMapping' não consegue resolver a instancia de ServiceFactory
    builder.RegisterType(dbContextType).As(typeof(DbContext)).InstancePerRequest();

    // (b) COM ESSA LINHA, O METODO 'RegisterMapping' consegue obter uma instancia de ServiceFactory
    //builder.RegisterType(dbContextType).As(typeof(DbContext)).InstancePerRequest("myrequest");

    builder.RegisterType<RepositoryFactory>().As<IRepositoryFactory>();
    builder.RegisterType<ServiceFactory>().As<IServiceFactory>();
    builder.RegisterApiControllers(assembly);
}

private void RegisterMapping()
{
    // usando (a) no metodo 'ConfigureContainer' temos um erro:
    // 'No scope with a Tag matching AutofacWebRequest'
    var serviceFactory = Container.Resolve<IServiceFactory>();
    Mapper.Initialize(cfg => ConfigureMapping(cfg, serviceFactory));

    // usando (b) no metodo 'ConfigureContainer' conseguimos resolver ServiceFactory, porém é injetado instancias diferentes de DbContext
    // o que faz com que o mapeamento dentro de 'ConfigureMapping' gere o erro: 
    // 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker'
    //using (var scope = Container.BeginLifetimeScope("myrequest"))
    //{
    //    var serviceFactory = scope.Resolve<IServiceFactory>();
    //    Mapper.Initialize(cfg => ConfigureMapping(cfg, serviceFactory));
    //}
}
The Configure(new ContainerBuilder()) method is called in Global.asax: DbAccessWrapper.Init(new VaiQueConfig()); where the new VaiQueConfig() constructor calls the Configure method by passing an instance of ContainerBuilder

    
asked by anonymous 03.05.2018 / 12:56

0 answers