aspnet / DependencyInjection

[Archived] Contains common DI abstractions that ASP.NET Core and Entity Framework Core use. Project moved to https://github.com/aspnet/Extensions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to implement a multitenant application ? (in aspnetcore)

valeriob opened this issue · comments

Hi,
i have a multi tenant application in owin/katana. In the pipeline i have a step after the container scope has been instantiated where i can inject an additional service based on the url (or whatever on the request).
This approach works very well, but i'm not able to replicate it in AspNetCore.
I tried a pipeline step where i replaced the container like this (i'm using autofac) :

        Task RegisterTenantDatabase(HttpContext context, Func<Task> next)
        {
            var tenantId = context.GetTenantId();
            var scope = (ILifetimeScope)context.RequestServices.GetService(typeof(ILifetimeScope));
            using (var requestScope = scope.BeginLifetimeScope())
            {
                RegisterDocumentSessionPerRequest(context, tenantId, requestScope);
                context.RequestServices = new AutofacServiceProvider(requestScope);
            }
            return next.Invoke();
        }

but without luck, if i look at components inside, i guess it misses the whole pipeline because i land in a white page 😄

Ho do you do that in aspnetcore ?

Just my opinion about the new approach to di in aspnetcore and other ms frameworks like ef, i think pendulum has swung too far down on the ioc path.
I've seen many singleton registered all around and so much abuse of Service Locator pattern, those make things very hard to reason about and follow dependencies.
I'm very familiar with SOLID and Dependency Inversion principles for years and i think that using an ioc container so early in a pipeline is a mistake, because it separates two things that should really be together : the request-response pipeline and scoping of instance lifetime. the first is a pure functional approach where you do not need IoC, just a few function to allow ppl to hook stuff. An ioc container should only be introduced by an app framework if it please, like mvc. People should not have control over lifetime choices of some internal components, and should allow to instantiate things the way they like.

Thanks

It's definitely possible to do it and many others have done it successfully. @sebastienros can explain how orchard does it.

Also, this isn't a DI issue and should probably be filed at http://github.com/aspnet/Home.

Thanks @davidfowl i will do that !

opened by mistake :D