본문 바로가기

.NET/MVC.NET

Autofac을 이용한 Multi tenant구현

£
많은 개발자들이 커스터 마이징의 늪에서 고통을 받고 있다. 예를 들면 어떤 교육사이트가 있는데 A사는 이렇게 커스터 마이징 해달라 B사는 이렇게 …..
고객의 니즈가 각양각색으로 요구되면서 개발자들은 많은 고통과 어려움에 봉착하게 된다. 이러한 것들을 해결하기 위해 Multitenancy라는 아주 훌륭한 Framework들이 나왔다. 그중에  여기서는 Autofac에서 제시한 프레임워크를 사용할 것이다.

£Autofac에서 Multitenancy를 구현하기 위해서는 기본적으로 다음 네가지의 것들이 필요하다 .
프로젝트에 필요한 Assembly참조
Dependencies(의존성) 등록(base 그리고 override)
Tenant Identification
         •식별된 tenant 들에 대한 Resolve Dependency 
£Autofac.dll (autofac을 사용하기 위한 Assembly로써 가장 기본이됨)
£AutofacContrib.Multitenant.dll(Multitenancy를 구현하기 위한 구현체들)
£Autofac.Intergration.Mvc(MVC에 통합된 구현체들) 

£AutofacContrib.Multitenant는 새로운 컨테이너 타입 AutofacContrib.Multitenant.MultitenantContainer를 포함하고 있습니다. 이 컨테이너는 Application단에 Defaultstenantoverride구현체를 관리합니다.

£Dependency를 등록하려면 다음의 단계들이 필요합니다.
Application Level Deafult  Container를 생성합니다.
Tenant identification strategy인스턴스화 합니다.
Multitenant Container를 생성합니다.
Tenant의 특별한 override된 구현체를 등록합니다.

£아래는  Global.asax의 간단한 등록 예제입니다.

var builder = new ContainerBuilder();                         

builder.RegisterControllers(Assembly.GetExecutingAssembly()); 

var container = builder.Build();             

var tenantIdentifier = new RequestParameterStrategy();             

var mtc = new MultitenantContainer(tenantIdentifier, container);             

mtc.ConfigureTenant("test1", d =>  d.RegisterType<Home2Controller>().As<HomeController>());            

 DependencyResolver.SetResolver(new AutofacDependencyResolver(mtc)); 

 £Tenant의 특별한 요구들에 해결하기 위해 Autofac은 어떤 tenant가 요청을 했는지 식별해야합니다이러한 tenant를 식별하기 위해서는 ItenantIdentificationStrategy 인터페이스를 구현해야 합니다아래는 2차도메인으로 Tenant를 식별하는 간단한 구현체 클래스를 보여줍니다.

 

 public class RequestParameterStrategy : ITenantIdentificationStrategy

    {

        public bool TryIdentifyTenant(out object tenantId)

        {

  tenantId = null;

            try

            {

                var context = HttpContext.Current;

                if (context != null && context.Request != null)

                {

                    tenantId = context.Request.Url.Host.Split('.').FirstOrDefault();

                }

            }

            catch (HttpException)

            {

                // Happens at app startup in IIS 7.0

            }

            return tenantId != null;

        }

    }

£Tenant의 특별한 컨트롤러들을 등록 하기 위해서는  Default를 상속받다 구현해야합니다. 그리고 아래와같이 컨트롤들을 등록해 줘야합니다.

mtc.ConfigureTenant("test1", d =>  d.RegisterType<Home2Controller>().As<HomeController>());