public void InstancePerTenant_RespectsLifetimeScope()
        {
            var strategy = new StubTenantIdentificationStrategy()
            {
                TenantId = "tenant1"
            };
            var builder = new ContainerBuilder();

            builder.RegisterType <StubDependency1Impl1>().As <IStubDependency1>().InstancePerTenant();
            var mtc = new MultitenantContainer(strategy, builder.Build());

            // Two resolutions for a single tenant
            var dep1 = mtc.Resolve <IStubDependency1>();
            var dep2 = mtc.Resolve <IStubDependency1>();

            // One resolution for a different tenant
            strategy.TenantId = "tenant2";
            var dep3 = mtc.Resolve <IStubDependency1>();

            Assert.Same(dep1, dep2);
            Assert.NotSame(dep1, dep3);
        }
        public void Resolve_ApplicationLevelSingleton()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <StubDependency1Impl1>().As <IStubDependency1>().SingleInstance();
            var strategy = new StubTenantIdentificationStrategy()
            {
                TenantId = "tenant1",
            };
            var mtc = new MultitenantContainer(strategy, builder.Build());

            // Two resolutions for a single tenant
            var dep1 = mtc.Resolve <IStubDependency1>();
            var dep2 = mtc.Resolve <IStubDependency1>();

            // One resolution for a different tenant
            strategy.TenantId = "tenant2";
            var dep3 = mtc.Resolve <IStubDependency1>();

            Assert.Same(dep1, dep2);
            Assert.Same(dep1, dep3);
        }
        public void GetTenants_CheckRegistered()
        {
            var strategy = new StubTenantIdentificationStrategy()
            {
                TenantId = "tenant1",
            };
            var mtc = new MultitenantContainer(strategy, new ContainerBuilder().Build());

            mtc.ConfigureTenant("tenant1", b => b.RegisterType <StubDependency1Impl1>().AsImplementedInterfaces());
            mtc.ConfigureTenant("tenant2", b => b.RegisterType <StubDependency1Impl2>().AsImplementedInterfaces());
            mtc.ConfigureTenant("tenant3", b => b.RegisterType <StubDependency1Impl3>().AsImplementedInterfaces());

            var registeredTenants = mtc.GetTenants().ToList();

            Assert.Equal(registeredTenants.Count, 3);

            foreach (var tenantId in registeredTenants)
            {
                var scope = mtc.GetTenantScope(tenantId);
                Assert.NotNull(scope);
            }
        }
Exemplo n.º 4
0
        public void InstancePerTenant_RespectsLifetimeScope()
        {
            var strategy = new StubTenantIdentificationStrategy()
            {
                TenantId = "tenant1"
            };
            var builder = new ContainerBuilder();

            builder.RegisterType <StubDependency1Impl1>().As <IStubDependency1>().InstancePerTenant();
            var mtc = new MultitenantContainer(strategy, builder.Build());

            // Two resolutions for a single tenant
            var dep1 = mtc.Resolve <IStubDependency1>();
            var dep2 = mtc.Resolve <IStubDependency1>();

            // One resolution for a different tenant
            strategy.TenantId = "tenant2";
            var dep3 = mtc.Resolve <IStubDependency1>();

            Assert.AreSame(dep1, dep2, "The two dependencies resolved for the first tenant should be the same.");
            Assert.AreNotSame(dep1, dep3, "The dependencies resolved across tenants should not be the same.");
        }
Exemplo n.º 5
0
        private static IContainer ConfigureDependencies()
        {
            //注册依赖
            var builder = new ContainerBuilder();

            builder.RegisterType <Consumer>().As <IDependencyConsumer>().InstancePerDependency();
            builder.RegisterType <BaseDependency>().As <IDependency>().SingleInstance();
            var appContainer = builder.Build();

            //创建多租户容器
            var mtc = new MultitenantContainer(_tenantIdentifier, appContainer);

            //重写租户1,注册依赖
            mtc.ConfigureTenant('1', b => b.RegisterType <Tenant1Dependency>().As <IDependency>().InstancePerDependency());

            //重写租户2,注册依赖
            mtc.ConfigureTenant('2', b => b.RegisterType <Tenant2Dependency>().As <IDependency>().InstancePerDependency());

            //重写默认租户,注册依赖
            mtc.ConfigureTenant(null, b => b.RegisterType <DefaultTenantDependency>().As <IDependency>().SingleInstance());

            return(mtc);
        }
Exemplo n.º 6
0
        public static MultitenantContainer Config(IContainer container)
        {
            var strategy = new MyTenantStrategy(container.Resolve <ITenantContextService>(), container.Resolve <ITenantIdRepository>());

            var mtc = new MultitenantContainer(strategy, container);

            mtc.ConfigureTenant(null, cfg =>
            {
                cfg.RegisterType <BarService>().As <IBarService>().SingleInstance();
            });

            mtc.ConfigureTenant("1", cfg =>
            {
                cfg.RegisterType <Bar1Service>().As <IBarService>().SingleInstance();
            });

            mtc.ConfigureTenant("2", cfg =>
            {
                cfg.RegisterType <Bar2Service>().As <IBarService>().SingleInstance();
            });

            return(mtc);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Registers tenant-specific all public classes decorated with attributes DomainService, Transformer, Validator,
        /// Repository, RequestHandler, EventHandler, DataProvider and ExecutionContextInitialiser
        /// within all specified assemblies
        /// </summary>
        /// <param name="container">Autofac multitenant container</param>
        /// <param name="tenantId">Tenant Id</param>
        /// <param name="assemblies">List of assemblies</param>
        public static void RegisterAll(
            this MultitenantContainer container,
            object tenantId,
            params Assembly[] assemblies)
        {
            container.NotNull(nameof(container));
            tenantId.NotNull(nameof(tenantId));
            assemblies.NotNullOrEmpty(nameof(assemblies));

            container.ConfigureTenant(tenantId,
                                      b =>
            {
                b.RegisterAllDomainServices(assemblies);
                b.RegisterAllTransformers(assemblies);
                b.RegisterAllRepositories(assemblies);
                b.RegisterAllValidators(assemblies);
                b.RegisterAllRequestHandlers(assemblies);
                b.RegisterAllEventHandlers(assemblies);
                b.RegisterAllDataProviders(assemblies);
                b.RegisterAllExecutionContextInitialisers(assemblies);
                b.RegisterAllSpecifications(assemblies);
            });
        }
Exemplo n.º 8
0
        public void Dispose_DisposesTenantLifetimeScopes()
        {
            var appDependency    = new StubDisposableDependency();
            var tenantDependency = new StubDisposableDependency();
            var builder          = new ContainerBuilder();

            builder.RegisterInstance(appDependency).OwnedByLifetimeScope();
            var strategy = new StubTenantIdentificationStrategy()
            {
                TenantId = "tenant1"
            };
            var mtc = new MultitenantContainer(strategy, builder.Build());

            mtc.ConfigureTenant("tenant1", b => b.RegisterInstance(tenantDependency).OwnedByLifetimeScope());

            // Resolve the tenant dependency so it's added to the list of things to dispose.
            // If you don't do this, it won't be queued for disposal and the test fails.
            mtc.Resolve <StubDisposableDependency>();

            mtc.Dispose();
            Assert.IsTrue(appDependency.IsDisposed, "The application scope didn't run Dispose.");
            Assert.IsTrue(tenantDependency.IsDisposed, "The tenant scope didn't run Dispose.");
        }
Exemplo n.º 9
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var containerBuilder = new ContainerBuilder();

            containerBuilder.Populate(services);

            var container = containerBuilder.Build();

            var mtc = new MultitenantContainer(
                new TenantIdentitificationStrategy(container.Resolve <IHttpContextAccessor>()), container);

            mtc.ConfigureTenant(TenantIdentitificationStrategy.TenantIds[0], builder => builder
                                .RegisterType <TenantOneService>().As <ITenantService>());

            mtc.ConfigureTenant(TenantIdentitificationStrategy.TenantIds[1], builder => builder
                                .RegisterType <TenantTwoService>().As <ITenantService>());

            Startup.ApplicationContainer = mtc;

            return(new AutofacServiceProvider(mtc));
        }
Exemplo n.º 10
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            var builder = new ContainerBuilder();

            builder.Populate(services);
            builder.Register(ctx => new Dependency {
                Id = "base"
            }).As <IDependency>();
            var container = builder.Build();
            var strategy  = new QueryStringTenantIdentificationStrategy(container.Resolve <IHttpContextAccessor>());
            var mtc       = new MultitenantContainer(strategy, container);

            mtc.ConfigureTenant("a", cb => cb.Register(ctx => new Dependency {
                Id = "a"
            }).As <IDependency>());
            mtc.ConfigureTenant("b", cb => cb.Register(ctx => new Dependency {
                Id = "b"
            }).As <IDependency>());
            Startup.ApplicationContainer = mtc;
            return(new AutofacServiceProvider(mtc));
        }
Exemplo n.º 11
0
        public static MultitenantContainer ConfigureMultitenantContainer(IContainer container)
        {
            var strategy = new QueryStringTenantIdentificationStrategy(container.Resolve <IHttpContextAccessor>(),
                                                                       container.Resolve <ILogger <QueryStringTenantIdentificationStrategy> >());

            var multitenantContainer = new MultitenantContainer(strategy, container);

            multitenantContainer.ConfigureTenant(
                "a",
                cb => cb
                .RegisterType <Dependency>()
                .As <IDependency>()
                .WithProperty("Id", "a")
                .InstancePerLifetimeScope());
            multitenantContainer.ConfigureTenant(
                "b",
                cb => cb
                .RegisterType <Dependency>()
                .As <IDependency>()
                .WithProperty("Id", "b")
                .InstancePerLifetimeScope());

            return(multitenantContainer);
        }
Exemplo n.º 12
0
 public MultiTenantConfigureOnDemandStartupFilter(ITenantIdentificationStrategy tenantIdentificationStrategy, MultitenantContainer multitenantContainer)
 {
     this.tenantIdentificationStrategy = tenantIdentificationStrategy;
     this.multitenantContainer         = multitenantContainer;
 }
Exemplo n.º 13
0
        private static MultitenantContainer CreateContainer(IContainer container)
        {
            var mtc = new MultitenantContainer(Mock.Of <ITenantIdentificationStrategy>(), container);

            return(mtc);
        }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MultitenantRequestServicesMiddleware"/> class.
 /// </summary>
 /// <param name="next">The next step in the request pipeline.</param>
 /// <param name="contextAccessor">The <see cref="IHttpContextAccessor"/> to set up with the current request context.</param>
 /// <param name="multitenantContainer">The <see cref="MultitenantContainer"/> registered through <see cref="AutofacMultitenantServiceProviderFactory"/>.</param>
 public MultitenantRequestServicesMiddleware(RequestDelegate next, IHttpContextAccessor contextAccessor, MultitenantContainer multitenantContainer)
 {
     _next                 = next;
     _contextAccessor      = contextAccessor;
     _multitenantContainer = multitenantContainer;
 }
 /// <summary>
 /// Register dependencies to the multitenant container
 /// </summary>
 /// <param name="container">The Autofac multi tenant container</param>
 /// <remarks>
 /// Default implementation register all API objects
 /// </remarks>
 protected virtual void RegisterDependencies(
     MultitenantContainer container)
 {
     container.RegisterAll(TenantId, this.ThisAssembly);
 }
        /// <summary>
        /// Adds tenant-specific registrations to the container
        /// </summary>
        /// <param name="container">Autofac multitenant container</param>
        public void Load(MultitenantContainer container)
        {
            container.NotNull(nameof(container));

            RegisterDependencies(container);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Handles the global application startup event.
        /// </summary>
        protected void Application_Start()
        {
            // Create the tenant ID strategy. Required for multitenant integration.
            var tenantIdStrategy = new RequestParameterTenantIdentificationStrategy("tenant");

            // Register application-level dependencies and controllers. Note that
            // we are manually registering controllers rather than all at the same
            // time because some of the controllers in this sample application
            // are for specific tenants.
            var builder = new ContainerBuilder();

            builder.RegisterType <HomeController>();
            builder.RegisterType <BaseDependency>().As <IDependency>();

            // Adding the tenant ID strategy into the container so controllers
            // can display output about the current tenant.
            builder.RegisterInstance(tenantIdStrategy).As <ITenantIdentificationStrategy>();

            // The service client is not different per tenant because
            // the service itself is multitenant - one client for all
            // the tenants and the service implementation switches.
            builder.Register(c => new ChannelFactory <IMultitenantService>(new BasicHttpBinding(), new EndpointAddress("http://localhost:63578/MultitenantService.svc"))).SingleInstance();
            builder.Register(c => new ChannelFactory <IMetadataConsumer>(new WSHttpBinding(), new EndpointAddress("http://localhost:63578/MetadataConsumer.svc"))).SingleInstance();

            // Register an endpoint behavior on the client channel factory that
            // will propagate the tenant ID across the wire in a message header.
            // On the service side, you'll need to read the header from incoming
            // message headers to reconstitute the incoming tenant ID.
            builder.Register(c =>
            {
                var factory      = c.Resolve <ChannelFactory <IMultitenantService> >();
                factory.Opening += (sender, args) => factory.Endpoint.Behaviors.Add(new TenantPropagationBehavior <string>(tenantIdStrategy));
                return(factory.CreateChannel());
            }).InstancePerHttpRequest();
            builder.Register(c =>
            {
                var factory      = c.Resolve <ChannelFactory <IMetadataConsumer> >();
                factory.Opening += (sender, args) => factory.Endpoint.Behaviors.Add(new TenantPropagationBehavior <string>(tenantIdStrategy));
                return(factory.CreateChannel());
            }).InstancePerHttpRequest();

            // Create the multitenant container based on the application
            // defaults - here's where the multitenant bits truly come into play.
            var mtc = new MultitenantContainer(tenantIdStrategy, builder.Build());

            // Notice we configure tenant IDs as strings below because the tenant
            // identification strategy retrieves string values from the request
            // context. To use strongly-typed tenant IDs, create a custom tenant
            // identification strategy that returns the appropriate type.

            // Configure overrides for tenant 1 - dependencies, controllers, etc.
            mtc.ConfigureTenant("1",
                                b =>
            {
                b.RegisterType <Tenant1Dependency>().As <IDependency>().InstancePerDependency();
                b.RegisterType <Tenant1Controller>().As <HomeController>();
            });

            // Configure overrides for tenant 2 - dependencies, controllers, etc.
            mtc.ConfigureTenant("2",
                                b =>
            {
                b.RegisterType <Tenant2Dependency>().As <IDependency>().SingleInstance();
                b.RegisterType <Tenant2Controller>().As <HomeController>();
            });

            // Configure overrides for the default tenant. That means the default
            // tenant will have some different dependencies than other unconfigured
            // tenants.
            mtc.ConfigureTenant(null, b => b.RegisterType <DefaultTenantDependency>().As <IDependency>().SingleInstance());

            // Create the dependency resolver using the
            // multitenant container instead of the application container.
            DependencyResolver.SetResolver(new AutofacDependencyResolver(mtc));

            // Perform the standard MVC setup requirements.
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Handles the global application startup event.
        /// </summary>
        protected void Application_Start(object sender, EventArgs e)
        {
            // Create the tenant ID strategy. Required for multitenant integration.
            var tenantIdStrategy = new OperationContextTenantIdentificationStrategy();

            // Register application-level dependencies and service implementations.
            // Note that we are registering the services as the interface type
            // because the .svc files refer to the interfaces. We could potentially
            // use named service types as well.
            var builder = new ContainerBuilder();

            builder.RegisterType <BaseImplementation>().As <IMultitenantService>();
            builder.RegisterType <BaseImplementation>().As <IMetadataConsumer>();
            builder.RegisterType <BaseDependency>().As <IDependency>();

            // Adding the tenant ID strategy into the container so services
            // can return output about the current tenant.
            builder.RegisterInstance(tenantIdStrategy).As <ITenantIdentificationStrategy>();

            // Create the multitenant container based on the application
            // defaults - here's where the multitenant bits truly come into play.
            var mtc = new MultitenantContainer(tenantIdStrategy, builder.Build());

            // Notice we configure tenant IDs as strings below because the tenant
            // identification strategy retrieves string values from the message
            // headers.

            // Configure overrides for tenant 1 - dependencies, service implementations, etc.
            mtc.ConfigureTenant("1",
                                b =>
            {
                b.RegisterType <Tenant1Dependency>().As <IDependency>().InstancePerDependency();
                b.RegisterType <Tenant1Implementation>().As <IMultitenantService>();
                b.RegisterType <Tenant1Implementation>().As <IMetadataConsumer>();
            });

            // Configure overrides for tenant 2 - dependencies, service implementations, etc.
            mtc.ConfigureTenant("2",
                                b =>
            {
                b.RegisterType <Tenant2Dependency>().As <IDependency>().SingleInstance();
                b.RegisterType <Tenant2Implementation>().As <IMultitenantService>();
                b.RegisterType <Tenant2Implementation>().As <IMetadataConsumer>();
            });

            // Configure overrides for the default tenant. That means the default
            // tenant will have some different dependencies than other unconfigured
            // tenants.
            mtc.ConfigureTenant(null, b => b.RegisterType <DefaultTenantDependency>().As <IDependency>().SingleInstance());

            // Multitenant service hosting requires use of a different service implementation
            // data provider that will allow you to define a metadata buddy class that isn't
            // tenant-specific.
            AutofacHostFactory.ServiceImplementationDataProvider = new MultitenantServiceImplementationDataProvider();

            // Add a behavior to service hosts that get created so incoming messages
            // get inspected and the tenant ID can be parsed from message headers.
            // For multitenancy to work, you need to know for which tenant a
            // given request is being made. In this case, the incoming message headers
            // expect to see a string for the tenant ID; if your tenant ID coming
            // from clients is different, change that here.
            AutofacHostFactory.HostConfigurationAction =
                host =>
                host.Opening += (s, args) =>
                                host.Description.Behaviors.Add(new TenantPropagationBehavior <string>(tenantIdStrategy));

            // Finally, set the host factory application container on the multitenant
            // WCF host to a multitenant container. This is similar to standard
            // Autofac WCF integration.
            AutofacHostFactory.Container = mtc;

            // Note that the .svc file for your service needs to use the
            // Autofac.Extras.Multitenant.Wcf.AutofacServiceHostFactory or
            // Autofac.Extras.Multitenant.Wcf.AutofacWebServiceHostFactory rather
            // than the standard Autofac host factories.
        }
Exemplo n.º 19
0
 public static AutofacServiceProvider NewTenantScope(this MultitenantContainer mtc, string tenantName)
 {
     mtc.ConfigureOnDemand(tenantName);
     return(new AutofacServiceProvider(mtc.GetTenantScope(tenantName).BeginLifetimeScope("non-request")));
 }
Exemplo n.º 20
0
        public void UseAutofacMultitenantRequestServices_NullBuilder()
        {
            var mtc = new MultitenantContainer(Mock.Of <ITenantIdentificationStrategy>(), new ContainerBuilder().Build());

            Assert.Throws <ArgumentNullException>(() => AutofacMultitenantWebHostBuilderExtensions.UseAutofacMultitenantRequestServices(null));
        }
 public MultiTenantJobActivator(MultitenantContainer mtc, object tenantId)
 {
     _mtc      = mtc;
     _tenantId = tenantId;
 }
 public AspNetCoreMultiTenantJobActivator(MultitenantContainer mtc, object tenantId)
 {
     _serviceScopeFactory = mtc.GetTenantScope(tenantId);
     _tenantId            = tenantId;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AutofacMultitenantServiceProvider"/> class.
 /// </summary>
 /// <param name="multitenantContainer">The <see cref="MultitenantContainer"/>.</param>
 public AutofacMultitenantServiceProvider(MultitenantContainer multitenantContainer)
     : base(multitenantContainer)
 {
 }
Exemplo n.º 24
0
 public MvcTenantScopeJobRunner(MultitenantContainer resolver, IEnumerable <Tenant> tenants)
 {
     _tenants  = tenants;
     _resolver = resolver;
 }
        private static void IoCRegistrationWithMultiTenancy()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <Pipeline <Withdrawal> >().As <IPipeline <Withdrawal> >();

            var container = builder.Build();

            var tenantIdentifier = new SimpleTenantIdentificationStrategy();

            var mtc = new MultitenantContainer(tenantIdentifier, container);

            mtc.ConfigureTenant("1", cb => cb.Register(ctx =>
                                                       new Pipeline <Withdrawal>()
                                                       .Register(new DailyLimit100())
                                                       .Register(new AboveMaximum1000())
                                                       .Register(new BelowMinimumAllowed100())).As <IPipeline <Withdrawal> >());

            mtc.ConfigureTenant("2", cb => cb.Register(ctx =>
                                                       new Pipeline <Withdrawal>()
                                                       .Register(new DailyLimit50())
                                                       .Register(new AboveMaximum100())
                                                       .Register(new BelowMinimumAllowed20())).As <IPipeline <Withdrawal> >());


            //Tenant 1 (Site 1)
            tenantIdentifier.SetTenant(TenantName.Site1);

            var withdrawalPipelineTenant1 = mtc.Resolve <IPipeline <Withdrawal> >();

            //Valid withdrawal limit is amount > 100 and amount < 1000.
            var validWithdrawal = new Withdrawal()
            {
                Amount = 150
            };
            var inValidWithdrawalLimit = new Withdrawal()
            {
                Amount = 50
            };

            var validContext = new Context <Withdrawal>()
            {
                item = validWithdrawal
            };
            var result = withdrawalPipelineTenant1.Execute(validContext);

            Console.WriteLine(string.Format("The request for Tenant 1 withdrawal is valid? {0}", result));

            var invalidContext = new Context <Withdrawal> {
                item = inValidWithdrawalLimit
            };

            result = withdrawalPipelineTenant1.Execute(invalidContext);
            Console.WriteLine(string.Format("The request for Tenant 1 withdrawal is valid? {0}", result));

            //Tenant 2 (Site 2)
            tenantIdentifier.SetTenant(TenantName.Site2);

            var withdrawalPipelineTenant2 = mtc.Resolve <IPipeline <Withdrawal> >();

            //Valid withdrawal limit is amount > 50 and amount < 100.
            validWithdrawal = new Withdrawal()
            {
                Amount = 60
            };
            inValidWithdrawalLimit = new Withdrawal()
            {
                Amount = 10
            };

            validContext = new Context <Withdrawal>()
            {
                item = validWithdrawal
            };
            result = withdrawalPipelineTenant2.Execute(validContext);
            Console.WriteLine(string.Format("The request for Tenant 2 withdrawal is valid? {0}", result));

            invalidContext = new Context <Withdrawal> {
                item = inValidWithdrawalLimit
            };
            result = withdrawalPipelineTenant2.Execute(invalidContext);
            Console.WriteLine(string.Format("The request for Tenant 2 withdrawal is valid? {0}", result));
        }
Exemplo n.º 26
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // DataContext
            builder.Register(MultiTenantDataContextFactory.Create).As <GridDataContext>().As <IDbContext>().InstancePerRequest();
            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest();

            // Repositories

            // Attendance
            builder.RegisterType <AttendanceRepository>().As <IAttendanceRepository>().InstancePerRequest();

            // Auth
            builder.RegisterType <TokenRepository>().As <ITokenRepository>().InstancePerRequest();

            //Company
            builder.RegisterType <AwardRepository>().As <IAwardRepository>().InstancePerRequest();
            builder.RegisterType <EmailTemplateRepository>().As <IEmailTemplateRepository>().InstancePerRequest();
            builder.RegisterType <LocationRepository>().As <ILocationRepository>().InstancePerRequest();
            builder.RegisterType <PermissionRepository>().As <IPermissionRepository>().InstancePerRequest();
            builder.RegisterType <RoleMemberRepository>().As <IRoleMemberRepository>().InstancePerRequest();
            builder.RegisterType <RolePermissionRepository>().As <IRolePermissionRepository>().InstancePerRequest();
            builder.RegisterType <RoleRepository>().As <IRoleRepository>().InstancePerRequest();
            builder.RegisterType <TechnologyRepository>().As <ITechnologyRepository>().InstancePerRequest();

            // CRM
            builder.RegisterType <CRMAccountRepository>().As <ICRMAccountRepository>().InstancePerRequest();
            builder.RegisterType <CRMContactRepository>().As <ICRMContactRepository>().InstancePerRequest();
            builder.RegisterType <CRMLeadActivityRepository>().As <ICRMLeadActivityRepository>().InstancePerRequest();
            builder.RegisterType <CRMLeadCategoryRepository>().As <ICRMLeadCategoryRepository>().InstancePerRequest();
            builder.RegisterType <CRMLeadRepository>().As <ICRMLeadRepository>().InstancePerRequest();
            builder.RegisterType <CRMLeadSourceRepository>().As <ICRMLeadSourceRepository>().InstancePerRequest();
            builder.RegisterType <CRMLeadStatusRepository>().As <ICRMLeadStatusRepository>().InstancePerRequest();
            builder.RegisterType <CRMLeadTechnologyMapRepository>().As <ICRMLeadTechnologyMapRepository>().InstancePerRequest();
            builder.RegisterType <CRMPotentialActivityRepository>().As <ICRMPotentialActivityRepository>().InstancePerRequest();
            builder.RegisterType <CRMPotentialCategoryRepository>().As <ICRMPotentialCategoryRepository>().InstancePerRequest();
            builder.RegisterType <CRMPotentialRepository>().As <ICRMPotentialRepository>().InstancePerRequest();
            builder.RegisterType <CRMPotentialTechnologyMapRepository>().As <ICRMPotentialTechnologyMapRepository>().InstancePerRequest();
            builder.RegisterType <CRMSalesStageRepository>().As <ICRMSalesStageRepository>().InstancePerRequest();

            //HRMS
            builder.RegisterType <AccessRuleRepository>().As <IAccessRuleRepository>().InstancePerRequest();
            builder.RegisterType <CertificationRepository>().As <ICertificationRepository>().InstancePerRequest();
            builder.RegisterType <DepartmentRepository>().As <IDepartmentRepository>().InstancePerRequest();
            builder.RegisterType <DesignationRepository>().As <IDesignationRepository>().InstancePerRequest();
            builder.RegisterType <EmergencyContactRepository>().As <IEmergencyContactRepository>().InstancePerRequest();
            builder.RegisterType <EmployeeDependentRepository>().As <IEmployeeDependentRepository>().InstancePerRequest();
            builder.RegisterType <HobbyRepository>().As <IHobbyRepository>().InstancePerRequest();
            builder.RegisterType <LinkedAccountRepository>().As <ILinkedAccountRepository>().InstancePerRequest();
            builder.RegisterType <PersonRepository>().As <IPersonRepository>().InstancePerRequest();
            builder.RegisterType <ShiftRepository>().As <IShiftRepository>().InstancePerRequest();
            builder.RegisterType <SkillRepository>().As <ISkillRepository>().InstancePerRequest();
            builder.RegisterType <UserActivityRepository>().As <IUserActivityRepository>().InstancePerRequest();
            builder.RegisterType <UserAwardRepository>().As <IUserAwardRepository>().InstancePerRequest();
            builder.RegisterType <UserCertificationRepository>().As <IUserCertificationRepository>().InstancePerRequest();
            builder.RegisterType <UserDocumentRepository>().As <IUserDocumentRepository>().InstancePerRequest();
            builder.RegisterType <UserHobbyRepository>().As <IUserHobbyRepository>().InstancePerRequest();
            builder.RegisterType <UserRepository>().As <IUserRepository>().InstancePerRequest();
            builder.RegisterType <UserSkillRepository>().As <IUserSkillRepository>().InstancePerRequest();
            builder.RegisterType <UserTechnologyMapRepository>().As <IUserTechnologyMapRepository>().InstancePerRequest();

            // IMS
            builder.RegisterType <AssetAllocationRepository>().As <IAssetAllocationRepository>().InstancePerRequest();
            builder.RegisterType <AssetCategoryRepository>().As <IAssetCategoryRepository>().InstancePerRequest();
            builder.RegisterType <AssetDocumentRepository>().As <IAssetDocumentRepository>().InstancePerRequest();
            builder.RegisterType <AssetRepository>().As <IAssetRepository>().InstancePerRequest();
            builder.RegisterType <VendorRepository>().As <IVendorRepository>().InstancePerRequest();

            // IT
            builder.RegisterType <SoftwareCategoryRepository>().As <ISoftwareCategoryRepository>().InstancePerRequest();
            builder.RegisterType <SoftwareRepository>().As <ISoftwareRepository>().InstancePerRequest();
            builder.RegisterType <SystemSnapshotRepository>().As <ISystemSnapshotRepository>().InstancePerRequest();

            // KBS
            builder.RegisterType <ArticleAttachmentRepository>().As <IArticleAttachmentRepository>().InstancePerRequest();
            builder.RegisterType <ArticleRepository>().As <IArticleRepository>().InstancePerRequest();
            builder.RegisterType <ArticleVersionRepository>().As <IArticleVersionRepository>().InstancePerRequest();
            builder.RegisterType <CategoryRepository>().As <ICategoryRepository>().InstancePerRequest();
            builder.RegisterType <KeywordRepository>().As <IKeywordRepository>().InstancePerRequest();

            // LMS
            builder.RegisterType <HolidayRepository>().As <IHolidayRepository>().InstancePerRequest();
            builder.RegisterType <LeaveEntitlementRepository>().As <ILeaveEntitlementRepository>().InstancePerRequest();
            builder.RegisterType <LeaveEntitlementUpdateRepository>().As <ILeaveEntitlementUpdateRepository>().InstancePerRequest();
            builder.RegisterType <LeaveRepository>().As <ILeaveRepository>().InstancePerRequest();
            builder.RegisterType <LeaveTimePeriodRepository>().As <ILeaveTimePeriodRepository>().InstancePerRequest();
            builder.RegisterType <LeaveTypeRepository>().As <ILeaveTypeRepository>().InstancePerRequest();

            // Payroll
            builder.RegisterType <EmployeeSalaryRepository>().As <IEmployeeSalaryRepository>().InstancePerRequest();
            builder.RegisterType <SalaryComponentRepository>().As <ISalaryComponentRepository>().InstancePerRequest();

            //PMS
            builder.RegisterType <ProjectBillingRepository>().As <IProjectBillingRepository>().InstancePerRequest();
            builder.RegisterType <ProjectDocumentRepository>().As <IProjectDocumentRepository>().InstancePerRequest();
            builder.RegisterType <ProjectMemberRepository>().As <IProjectMemberRepository>().InstancePerRequest();
            builder.RegisterType <ProjectMileStoneRepository>().As <IProjectMileStoneRepository>().InstancePerRequest();
            builder.RegisterType <ProjectRepository>().As <IProjectRepository>().InstancePerRequest();
            builder.RegisterType <ProjectActivityRepository>().As <IProjectActivityRepository>().InstancePerRequest();
            builder.RegisterType <ProjectTechnologyMapRepository>().As <IProjectTechnologyMapRepository>().InstancePerRequest();
            builder.RegisterType <TaskEffortRepository>().As <ITaskEffortRepository>().InstancePerRequest();
            builder.RegisterType <TaskRepository>().As <ITaskRepository>().InstancePerRequest();
            builder.RegisterType <TimeSheetLineItemRepository>().As <ITimeSheetLineItemRepository>().InstancePerRequest();
            builder.RegisterType <TimeSheetRepository>().As <ITimeSheetRepository>().InstancePerRequest();
            builder.RegisterType <EstimateRepository>().As <IEstimateRepository>().InstancePerRequest();
            builder.RegisterType <EstimateLineItemRepository>().As <IEstimateLineItemRepository>().InstancePerRequest();
            builder.RegisterType <TimeSheetActivityRepository>().As <ITimeSheetActivityRepository>().InstancePerRequest();
            builder.RegisterType <TaskActivityRepository>().As <ITaskActivityRepository>().InstancePerRequest();

            //Recruit
            builder.RegisterType <CandidateActivityRepository>().As <ICandidateActivityRepository>().InstancePerRequest();
            builder.RegisterType <CandidateDesignationRepository>().As <ICandidateDesignationRepository>().InstancePerRequest();
            builder.RegisterType <CandidateDocumentRepository>().As <ICandidateDocumentRepository>().InstancePerRequest();
            builder.RegisterType <CandidateRepository>().As <ICandidateRepository>().InstancePerRequest();
            builder.RegisterType <CandidateTechnologyMapRepository>().As <ICandidateTechnologyMapRepository>().InstancePerRequest();
            builder.RegisterType <InterviewRoundRepository>().As <IInterviewRoundRepository>().InstancePerRequest();
            builder.RegisterType <InterviewRoundActivityRepository>().As <IInterviewRoundActivityRepository>().InstancePerRequest();
            builder.RegisterType <InterviewRoundDocumentRepository>().As <IInterviewRoundDocumentRepository>().InstancePerRequest();
            builder.RegisterType <JobOfferRepository>().As <IJobOfferRepository>().InstancePerRequest();
            builder.RegisterType <JobOpeningRepository>().As <IJobOpeningRepository>().InstancePerRequest();
            builder.RegisterType <ReferalRepository>().As <IReferalRepository>().InstancePerRequest();
            builder.RegisterType <RoundRepository>().As <IRoundRepository>().InstancePerRequest();

            // RMS
            builder.RegisterType <RequirementActivityRepository>().As <IRequirementActivityRepository>().InstancePerRequest();
            builder.RegisterType <RequirementCategoryRepository>().As <IRequirementCategoryRepository>().InstancePerRequest();
            builder.RegisterType <RequirementDocumentRepository>().As <IRequirementDocumentRepository>().InstancePerRequest();
            builder.RegisterType <RequirementRepository>().As <IRequirementRepository>().InstancePerRequest();
            builder.RegisterType <RequirementTechnologyMapRepository>().As <IRequirementTechnologyMapRepository>().InstancePerRequest();

            // Settings
            builder.RegisterType <GridUpdateRepository>().As <IGridUpdateRepository>().InstancePerRequest();
            builder.RegisterType <SettingRepository>().As <ISettingRepository>().InstancePerRequest();
            builder.RegisterType <UserFeedbackRepository>().As <IUserFeedbackRepository>().InstancePerRequest();
            builder.RegisterType <ApplicationRepository>().As <IApplicationRepository>().InstancePerRequest();

            // TicketDesk
            builder.RegisterType <TicketCategoryRepository>().As <ITicketCategoryRepository>().InstancePerRequest();
            builder.RegisterType <TicketSubCategoryRepository>().As <ITicketSubCategoryRepository>().InstancePerRequest();
            builder.RegisterType <TicketRepository>().As <ITicketRepository>().InstancePerRequest();
            builder.RegisterType <TicketActivityRepository>().As <ITicketActivityRepository>().InstancePerRequest();

            // TMS
            builder.RegisterType <MissedTimeSheetRepository>().As <IMissedTimeSheetRepository>().InstancePerRequest();

            //Social
            builder.RegisterType <PostRepository>().As <IPostRepository>().InstancePerRequest();
            builder.RegisterType <PostCommentRepository>().As <IPostCommentRepository>().InstancePerRequest();
            builder.RegisterType <PostLikeRepository>().As <IPostLikeRepository>().InstancePerRequest();

            // Business Services
            builder.RegisterType <CRMLeadService>().As <ICRMLeadService>().InstancePerRequest();
            builder.RegisterType <CRMPotentialService>().As <ICRMPotentialService>().InstancePerRequest();
            builder.RegisterType <CRMAccountService>().As <ICRMAccountService>().InstancePerRequest();
            builder.RegisterType <CRMContactService>().As <ICRMContactService>().InstancePerRequest();

            builder.RegisterType <RequirementService>().As <IRequirementService>().InstancePerRequest();
            builder.RegisterType <SettingsService>().As <ISettingsService>().InstancePerRequest();
            builder.RegisterType <UserService>().As <IUserService>().InstancePerRequest();
            builder.RegisterType <AssetService>().As <IAssetService>().InstancePerRequest();
            builder.RegisterType <LeaveService>().As <ILeaveService>().InstancePerRequest();
            builder.RegisterType <CandidateService>().As <ICandidateService>().InstancePerRequest();
            builder.RegisterType <RequirementService>().As <IRequirementService>().InstancePerRequest();
            builder.RegisterType <SettingsService>().As <ISettingsService>().InstancePerRequest();
            builder.RegisterType <TicketService>().As <ITicketService>().InstancePerRequest();
            builder.RegisterType <TimeSheetService>().As <ITimeSheetService>().InstancePerRequest();
            builder.RegisterType <TaskService>().As <ITaskService>().InstancePerRequest();
            builder.RegisterType <InterviewRoundService>().As <IInterviewRoundService>().InstancePerRequest();

            // Common Services
            builder.RegisterType <NotificationService>().As <INotificationService>().InstancePerRequest();
            builder.RegisterType <EmailComposerService>().As <EmailComposerService>().InstancePerRequest();

            // Register your MVC controllers.
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterControllers(typeof(ApiAreaRegistration).Assembly);

            // Register Injection for Filters
            builder.Register(c => new GlobalIdentityInjector(c.Resolve <IUserRepository>(), c.Resolve <IRoleMemberRepository>(), c.Resolve <IRolePermissionRepository>())).AsActionFilterFor <Controller>().InstancePerRequest();
            builder.RegisterFilterProvider();

            builder.RegisterType <SubDomainTenantIdentificationStrategy>().As <ITenantIdentificationStrategy>();

            var appContainer     = builder.Build();
            var tenantIdentifier = new SubDomainTenantIdentificationStrategy();
            var mtc = new MultitenantContainer(tenantIdentifier, appContainer);

            DependencyResolver.SetResolver(new AutofacDependencyResolver(mtc));

            // Register the Autofac middleware FIRST, then the Autofac MVC middleware.
            app.UseAutofacMiddleware(mtc);
            app.UseAutofacMvc();
        }
        public void AddAutofacMultitenantRequestServices_NullBuilder()
        {
            var mtc = new MultitenantContainer(Mock.Of <ITenantIdentificationStrategy>(), new ContainerBuilder().Build());

            Assert.Throws <ArgumentNullException>(() => AutofacMultitenantServiceCollectionExtensions.AddAutofacMultitenantRequestServices(null, () => mtc));
        }
            private void ConfigureTenants(MultitenantContainer mtc)
            {
                var serviceProvider = new AutofacServiceProvider(mtc);

                var hostingEnvironment   = serviceProvider.GetRequiredService <IHostEnvironment>();
                var config               = serviceProvider.GetRequiredService <IConfiguration>();
                var tenantConfigurations = serviceProvider.GetServices <ITenantConfiguration>();

                if (_options.AutoAddITenantConfigurationTenants)
                {
                    foreach (var tenantId in tenantConfigurations.Select(i => i.TenantId.ToString()))
                    {
                        if (!_options.Tenants.ContainsKey(tenantId))
                        {
                            _options.Tenants.Add(tenantId, null);
                        }
                    }
                }

                foreach (var kvp in _options.Tenants)
                {
                    var tenantConfiguration = tenantConfigurations.FirstOrDefault(i => i.TenantId.ToString() == kvp.Key);

                    var actionBuilder  = new ConfigurationActionBuilder();
                    var tenantServices = new ServiceCollection();

                    var defaultBuilder = new TenantBuilder(kvp.Key);

                    foreach (var ConfigureTenantsDelegate in _options.ConfigureTenantsDelegates)
                    {
                        ConfigureTenantsDelegate(defaultBuilder);
                    }

                    var tenantBuilder = new TenantBuilder(kvp.Key);
                    if (kvp.Value != null)
                    {
                        kvp.Value(tenantBuilder);
                    }

                    var options = new TenantBuilder(kvp.Key)
                    {
                        ConfigureAppConfigurationDelegate = (context, builder) =>
                        {
                            defaultBuilder.ConfigureAppConfigurationDelegate(context, builder);
                            tenantBuilder.ConfigureAppConfigurationDelegate(context, builder);
                            if (tenantConfiguration != null)
                            {
                                tenantConfiguration.ConfigureAppConfiguration(context, builder);
                            }
                        },
                        ConfigureServicesDelegate = (context, services) =>
                        {
                            defaultBuilder.ConfigureServicesDelegate(context, services);
                            tenantBuilder.ConfigureServicesDelegate(context, services);
                            if (tenantConfiguration != null)
                            {
                                tenantConfiguration.ConfigureServices(context, services);
                            }
                        },
                        InitializeDbAsyncDelegate = async(sp, cancellationToken) =>
                        {
                            await defaultBuilder.InitializeDbAsyncDelegate(sp, cancellationToken);

                            await tenantBuilder.InitializeDbAsyncDelegate(sp, cancellationToken);

                            if (tenantConfiguration != null)
                            {
                                await tenantConfiguration.InitializeDbAsync(sp, cancellationToken);
                            }
                        },
                        InitializeAsyncDelegate = async(sp, cancellationToken) =>
                        {
                            await defaultBuilder.InitializeAsyncDelegate(sp, cancellationToken);

                            await tenantBuilder.InitializeAsyncDelegate(sp, cancellationToken);

                            if (tenantConfiguration != null)
                            {
                                await tenantConfiguration.InitializeAsync(sp, cancellationToken);
                            }
                        }
                    };

                    foreach (var hostName in defaultBuilder.HostNames)
                    {
                        _options.HostMappings.Add(hostName, kvp.Key);
                    }

                    foreach (var hostName in tenantBuilder.HostNames)
                    {
                        _options.HostMappings.Add(hostName, kvp.Key);
                    }

                    var tenantConfig = TenantConfig.BuildTenantAppConfiguration(config, hostingEnvironment, kvp.Key, options.ConfigureAppConfigurationDelegate);

                    tenantServices.AddSingleton(tenantConfig);

                    var builderContext = new TenantBuilderContext(kvp.Key)
                    {
                        RootServiceProvider = serviceProvider,
                        Configuration       = tenantConfig,
                        HostingEnvironment  = hostingEnvironment
                    };

                    options.ConfigureServicesDelegate(builderContext, tenantServices);

                    actionBuilder.Add(b => b.Populate(tenantServices));
                    mtc.ConfigureTenant(kvp.Key, actionBuilder.Build());
                }
            }
Exemplo n.º 29
0
 public MultitenantContainerWrapper(MultitenantContainer mtc)
 {
     this.mtc = mtc;
 }
Exemplo n.º 30
0
 public MvcJobFactory(IContainer resolver, MultitenantContainer tenantResolver, IEnumerable <Tenant> tenants)
 {
     _resolver       = resolver;
     _tenantResolver = tenantResolver;
     _tenants        = tenants;
 }