What is the best practice to implement multi tenan

2019-02-04 03:36发布

问题:

I have a service with two different implementations and I would like to inject into the controllers constructor, depends on a criteria (at the moment the criteria is a simple value stored in session).

Here is what I got now...

Service interface:

public interface IService
{
    string GetSampleText();
}

Implementation #1:

public class FirstService : IService
{
    string GetSampleText()
    {
        return "First Service";
    }
}

Implementation #2:

public class SecondService : IService
{
    string GetSampleText()
    {
        return "Second Service";
    }
}

Registration in a Windsor installer class:

container.Register(AllTypes
  .FromAssemblyInDirectory(new AssemblyFilter(HttpRuntime.BinDirectory))
  .BasedOn<IService>()
  .WithService.FromInterface()
  .Configure(c => c.LifeStyle.Transient));

container.Kernel.AddHandlerSelector(new ServiceHandlerSelector());

I have implemented an IHandlerSelector:

public class ServiceHandlerSelector : IHandlerSelector { ... }

In the HasOpinionAbout method of this IHandlerSelector implementation I can decide which handler will be selected in the SelectHandler method (depends on the value from session).

Then the constructor injection is working fine on the controllers:

public MyController(IService service) { ... }

So I got a working solution, but I am not sure if it is the best way to do this.

Opinions? Suggestions?

Many thanks.

回答1:

You're on the right track with handler selectors. Here are some good articles on using them for multi-tenancy, you can use them for reference:

  • http://ayende.com/Blog/archive/2008/10/05/windsor-ihandlerselector.aspx
  • http://mikehadlow.blogspot.com/2008/11/multi-tenancy-part-2-components-and.html
  • http://bartreyserhove.blogspot.com/2009/02/building-multi-tenant-applications-with.html