protected override void Load(ContainerBuilder builder) { builder.RegisterGeneric(typeof (BasicRavenRepositoryWithGuid<>)) .As(typeof (IRepository<>)) .As(typeof (IRepositoryWithGuid<>)) .AsImplementedInterfaces(); builder.RegisterGeneric(typeof (Refrence<>)) .PropertiesAutowired() .AsSelf(); }
private static void SetAutofacContainer() { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterGeneric(typeof (UnitOfWork<>)).As(typeof (IUnitOfWork<>)); builder.RegisterGeneric(typeof (RepositoryBase<>)).As(typeof (IRepository<>)); builder.RegisterType(typeof (CategoryService)).As(typeof (ICategoryService)).InstancePerDependency(); builder.RegisterType(typeof (DepartmentService)).As(typeof (IDepartmentService)).InstancePerDependency(); IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
public void Register(Autofac.ContainerBuilder builder, SmartConfig config) { builder.RegisterGeneric(typeof(ITmpl <>)).As(typeof(IT <>)).InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(ITmpl <,>)).As(typeof(IT <,>)).InstancePerLifetimeScope(); builder.RegisterType <TestClass>().AsSelf().PropertiesAutowired().SingleInstance(); builder.RegisterType <TestClass2>().AsSelf().PropertiesAutowired().SingleInstance(); }
protected override void Load(ContainerBuilder builder) { //config builder.RegisterType<NHBoxConfig>().As<INHPropertiesProvider>().SingleInstance(); builder.RegisterType<RepositoryFinder>() .PropertiesAutowired() .InstancePerDependency(); //transformations builder.RegisterGeneric(typeof (FileBoxTransformation<>)).InstancePerDependency(); builder.RegisterGeneric(typeof (NHibernateBoxTransformation<,>)).InstancePerDependency(); builder.RegisterType<BackupsResolver>().InstancePerDependency(); //initialize evaluator builder.RegisterType<NHibernateBoxQueryEvaluator>() .PropertiesAutowired() .SingleInstance(); builder.RegisterGeneric(typeof(BoxQuery<>)) .OnActivated(x => { if (BoxedQueryRemoteExtensions.DefaultEvaluator == null) BoxedQueryRemoteExtensions.DefaultEvaluator = x.Context.Resolve<NHibernateBoxQueryEvaluator>().Evaluate; }); base.Load(builder); }
private void RegisterConfigSettings(Autofac.ContainerBuilder builder) { builder.RegisterGeneric(typeof(OptionsManager <>)).As(typeof(IOptions <>)).SingleInstance(); builder.RegisterGeneric(typeof(OptionsMonitor <>)).As(typeof(IOptionsMonitor <>)).SingleInstance(); builder.RegisterGeneric(typeof(OptionsSnapshot <>)).As(typeof(IOptionsSnapshot <>)).InstancePerLifetimeScope(); builder.RegisterInstance(_configuration).As <IConfiguration>(); }
private static void RegisterServices(ContainerBuilder builder) { builder.Register(x => new ApplicationDbContext()) .As<DbContext>() .InstancePerRequest(); builder.Register(x => new HttpCacheService()) .As<ICacheService>() .InstancePerRequest(); builder.Register(x => new HtmlSanitizerAdapter()) .As<ISanitizer>() .InstancePerRequest(); builder.Register(x => new IdentifierProvider()) .As<IIdentifierProvider>() .InstancePerRequest(); var servicesAssembly = Assembly.GetAssembly(typeof(IPostsService)); builder.RegisterAssemblyTypes(servicesAssembly).AsImplementedInterfaces(); builder.RegisterGeneric(typeof(DbRepository<>)).As(typeof(IDbRepository<>)).InstancePerRequest(); builder.RegisterGeneric(typeof(UserDbRepository<>)).As(typeof(IUserDbRepository<>)).InstancePerRequest(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AssignableTo<BaseController>().PropertiesAutowired(); }
private void RegisterCommonComponents(ContainerBuilder builder) { var mapper = Mapper ?? new MemoizingMappingManager(new AttributesMappingManager()); builder.RegisterInstance(mapper).As<IReadOnlyMappingManager>(); // builder.RegisterType<HttpRuntimeCache>().As<ISolrCache>(); builder.RegisterType<DefaultDocumentVisitor>().As<ISolrDocumentPropertyVisitor>(); builder.RegisterType<DefaultFieldParser>().As<ISolrFieldParser>(); builder.RegisterGeneric(typeof (SolrDocumentActivator<>)).As(typeof (ISolrDocumentActivator<>)); builder.RegisterGeneric(typeof (SolrDocumentResponseParser<>)).As(typeof (ISolrDocumentResponseParser<>)); builder.RegisterType<DefaultFieldSerializer>().As<ISolrFieldSerializer>(); builder.RegisterType<DefaultQuerySerializer>().As<ISolrQuerySerializer>(); builder.RegisterType<DefaultFacetQuerySerializer>().As<ISolrFacetQuerySerializer>(); builder.RegisterGeneric(typeof(DefaultResponseParser<>)).As(typeof(ISolrAbstractResponseParser<>)); builder.RegisterType<HeaderResponseParser<string>>().As<ISolrHeaderResponseParser>(); builder.RegisterType<ExtractResponseParser>().As<ISolrExtractResponseParser>(); foreach (var p in new[] { typeof (MappedPropertiesIsInSolrSchemaRule), typeof (RequiredFieldsAreMappedRule), typeof (UniqueKeyMatchesMappingRule), typeof(MultivaluedMappedToCollectionRule), }) builder.RegisterType(p).As<IValidationRule>(); builder.RegisterType<SolrSchemaParser>().As<ISolrSchemaParser>(); builder.RegisterGeneric(typeof(SolrMoreLikeThisHandlerQueryResultsParser<>)).As(typeof(ISolrMoreLikeThisHandlerQueryResultsParser<>)); builder.RegisterGeneric(typeof(SolrQueryExecuter<>)).As(typeof(ISolrQueryExecuter<>)); builder.RegisterGeneric(typeof (SolrDocumentSerializer<>)).As(typeof (ISolrDocumentSerializer<>)); builder.RegisterType<SolrDIHStatusParser>().As<ISolrDIHStatusParser>(); builder.RegisterType<MappingValidator>().As<IMappingValidator>(); builder.RegisterType<SolrStatusResponseParser>().As<ISolrStatusResponseParser>(); builder.RegisterType<SolrCoreAdmin>().As<ISolrCoreAdmin>(); builder.RegisterType<SolrDictionarySerializer>().As<ISolrDocumentSerializer<Dictionary<string, object>>>(); builder.RegisterType<SolrDictionaryDocumentResponseParser>().As<ISolrDocumentResponseParser<Dictionary<string, object>>>(); }
public static void Register() { var builder = new ContainerBuilder(); //cache manager builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("static_cache_manager").SingleInstance(); //builder.RegisterType<PerRequestCacheManager>().As<ICacheManager>().Named<ICacheManager>("per_request_cache_manager").InstancePerLifetimeScope(); // Since WCF requests does not have an http context we can not use InstancePerHttpRequest(). Instead we can use InstancePerLifetimeScope() // which is resolvable for both WCF and http requests. Autofac Wiki says : // The default ASP.NET and WCF integrations are set up so that InstancePerLifetimeScope() will attach a component to the current web request or service method call. // Register WCF services builder.RegisterType<UserService>().InstancePerLifetimeScope(); builder.RegisterType<GenericCharacteristicService>().InstancePerLifetimeScope(); builder.RegisterType<DataInfoService>().InstancePerLifetimeScope(); builder.RegisterType<Config>().InstancePerLifetimeScope(); builder.RegisterType<WebsiteSearcher>().As<ISearcher>().InstancePerLifetimeScope(); builder.RegisterType<DebugHelper>().As<IDebugHelper>().SingleInstance(); // database register var dbSettingsManager = new DatabaseSettingsManager(); var databaseSettings = dbSettingsManager.LoadSettings(); builder.RegisterType<DatabaseSettingsManager>().InstancePerDependency(); builder.Register(context => context.Resolve<DatabaseSettingsManager>().LoadSettings()).As<DatabaseSettings>().InstancePerLifetimeScope(); builder.Register(context => new EfDataProviderManager(context.Resolve<DatabaseSettings>())).As<IDataProviderManager>().InstancePerDependency(); // register for two types builder.Register(context => (IEfDataProvider)context.Resolve<IDataProviderManager>().DataProvider()).As<IDataProvider>().InstancePerDependency(); builder.Register(context => (IEfDataProvider)context.Resolve<IDataProviderManager>().DataProvider()).As<IEfDataProvider>().InstancePerDependency(); if (databaseSettings != null && databaseSettings.IsValid()) { //var efDataProviderManager = new EfDataProviderManager(dbSettingsManager.LoadSettings()); //var dataProvider = (IEfDataProvider)efDataProviderManager.DataProvider(); //dataProvider.Init(); builder.Register<IDatabase>(context => new CommerceDbContext(databaseSettings.DataConnectionString)).InstancePerLifetimeScope(); } else { builder.Register<IDatabase>(context => new CommerceDbContext(dbSettingsManager.LoadSettings().DataConnectionString)).InstancePerLifetimeScope(); } if (!dbSettingsManager.IsFaked) { builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope(); } else { builder.RegisterGeneric(typeof(FaskeRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope(); } //host.EnableDiscovery(); var container = builder.Build(); // make AutofacHostFactory.Container equal to EngineContext.Current // after it, should not set new container to AutofacHostFactory.Container or EngineContext.Current AutofacHostFactory.Container = container; EngineContext.Initialize(new AutofacContainerManager(container), new ContainerConfig(), false); }
public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) { var asm = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterGeneric(typeof(BaseEntityService<>)).As(typeof(IBaseEntityService<>)).InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(BaseEntityWithPictureService<,>)).As(typeof(IBaseEntityWithPictureService<,>)).InstancePerLifetimeScope(); builder.RegisterType<MobPageHeadBuilder>().As<MobPageHeadBuilder>().InstancePerRequest(); //register all the implemented services in various mob plugins builder.RegisterAssemblyTypes(asm).AsClosedTypesOf(typeof(BaseEntityService<>)) .AsImplementedInterfaces() .InstancePerDependency(); builder.RegisterAssemblyTypes(asm).AsClosedTypesOf(typeof(BaseEntityWithPictureService<,>)) .AsImplementedInterfaces() .InstancePerDependency(); //register all the repositories builder.RegisterGeneric(typeof(MobRepository<>)).As(typeof(IMobRepository<>)) .WithParameter(ResolvedParameter.ForNamed<IDbContext>(ContextName)) .InstancePerLifetimeScope(); }
public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder) { Singleton<IDependencyResolver>.Instance = new DependencyResolver(); string collectionString = "Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa;Trusted_Connection=False;"; builder.Register<IDbContext>(c => new WaterMoonContext(collectionString)).PerLifeStyle(ComponentLifeStyle.LifetimeScope); builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).PerLifeStyle(ComponentLifeStyle.LifetimeScope); builder.RegisterGeneric(typeof(PagedList<>)).As(typeof(IPagedList<>)).PerLifeStyle(ComponentLifeStyle.LifetimeScope); builder.RegisterType<DefualtMapping>().As<IMapping>().SingleInstance(); //注册所有实现IConsumer<>类型的对象 var consumers = typeFinder.FindClassesOfType(typeof(IConsumer<>)).ToList(); foreach (var consumer in consumers) { builder.RegisterType(consumer) .As(consumer.FindInterfaces((type, criteria) => { var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition()); return isMatch; }, typeof(IConsumer<>))) .PerLifeStyle(ComponentLifeStyle.LifetimeScope); } builder.RegisterType<EventPublisher>().As<IEventPublisher>().SingleInstance(); builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().SingleInstance(); builder.RegisterType<DemoService>().As<IDemoService>().PerLifeStyle(ComponentLifeStyle.LifetimeScope); }
public void Register(ContainerBuilder builder, ITypeFinder typeFinder) { var zergDataProvider = new ZergDataProvider(); zergDataProvider.InitDatabase(); var dataSettingsManager = new DataSettingsManager(); var dataProviderSettings = dataSettingsManager.LoadSettings(); //不同数据库对应不同的仓库 if (dataProviderSettings != null && dataProviderSettings.IsValid()) { builder.Register<IDbContext>(c => new CMSDbContext(dataProviderSettings.RawDataSettings["CMSConnection"])).Named<IDbContext>("CMS").InstancePerRequest(); builder.Register<IDbContext>(c => new CRMDbContext(dataProviderSettings.RawDataSettings["CRMConnection"])).Named<IDbContext>("CRM").InstancePerRequest(); builder.Register<IDbContext>(c => new TradingDbContext(dataProviderSettings.RawDataSettings["TradingConnection"])).Named<IDbContext>("Trading").InstancePerRequest(); builder.Register<IDbContext>(c => new EventDbContext(dataProviderSettings.RawDataSettings["EventConnection"])).Named<IDbContext>("Event").InstancePerRequest(); builder.Register<IDbContext>(c => new CommunityDbContext(dataProviderSettings.RawDataSettings["CommunityConnection"])).Named<IDbContext>("Community").InstancePerRequest(); } #region 不同的数据库对应不同仓库 var cmsParameter = new ResolvedParameter((pi, ctx) => pi.Name == "context", (pi, ctx) => ctx.ResolveNamed<IDbContext>("CMS")); var crmParameter = new ResolvedParameter((pi, ctx) => pi.Name == "context", (pi, ctx) => ctx.ResolveNamed<IDbContext>("CRM")); var tradingParameter = new ResolvedParameter((pi, ctx) => pi.Name == "context", (pi, ctx) => ctx.ResolveNamed<IDbContext>("Trading")); var eventPrameter = new ResolvedParameter((pi, ctx) => pi.Name == "context", (pi, ctx) => ctx.ResolveNamed<IDbContext>("Event")); var communityPrameter = new ResolvedParameter((pi, ctx) => pi.Name == "context", (pi, ctx) => ctx.ResolveNamed<IDbContext>("Community")); builder.RegisterGeneric(typeof(CMSRepository<>)) .WithParameter(cmsParameter) .As(typeof(ICMSRepository<>)) .InstancePerRequest(); builder.RegisterGeneric(typeof(CRMRepository<>)) .WithParameter(crmParameter) .As(typeof(ICRMRepository<>)) .InstancePerRequest(); builder.RegisterGeneric(typeof(TradingRepository<>)) .WithParameter(tradingParameter) .As(typeof(ITradingRepository<>)) .InstancePerRequest(); builder.RegisterGeneric(typeof(EventRepository<>)) .WithParameter(eventPrameter) .As(typeof(IEventRepository<>)) .InstancePerRequest(); builder.RegisterGeneric(typeof(CommunityRepository<>)) .WithParameter(communityPrameter) .As(typeof(ICommunityRepository<>)) .InstancePerRequest(); #endregion // builder.RegisterAssemblyTypes(typeFinder.GetAssemblies().ToArray()) // .Where(t =>!String.IsNullOrEmpty(t.Namespace)&& t.Namespace.StartsWith("CMS") && t.Name.Contains("Service")) // .WithParameter(repositeryParameter); }
public void Register(ContainerBuilder builder, SmartConfig config) { builder.RegisterType<Context.SampleDbContext>().As<DbContext>().InstancePerLifetimeScope(); builder.RegisterType<Context.OtherDbContext>().As<Context.IOtherDbContext>().InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(EFRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(EFRepository<,>)).As(typeof(IRepository<,>)).InstancePerLifetimeScope(); }
private static void RegisterServices(ContainerBuilder builder) { //var context = ; builder.Register(x => new ApplicationDbContext()) .As<DbContext>() .InstancePerRequest(); builder.Register(x => new HttpCacheService()) .As<ICacheService>() .InstancePerRequest(); /*builder.Register(x => context) .As<IdentityDbContext<ApplicationUser>>() .InstancePerRequest();*/ builder.Register(x => new IdentifierProvider()) .As<IIdentifierProvider>() .InstancePerRequest(); var servicesAssembly = Assembly.GetAssembly(typeof(ITestsService)); builder.RegisterAssemblyTypes(servicesAssembly).AsImplementedInterfaces(); builder.RegisterGeneric(typeof(DbRepository<>)) .As(typeof(IDbRepository<>)) .InstancePerRequest(); builder.RegisterGeneric(typeof(GenericRepository<,>)) .As(typeof(IDbGenericRepository<,>)) .InstancePerRequest(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AssignableTo<BaseController>().PropertiesAutowired(); }
public static void ConfigureContainer() { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetAssembly(typeof(AutofacConfig))); builder.Register(context => NhibernateConfig.GetSessionFactory()).As<ISessionFactory>().SingleInstance(); // Use a session per web request. builder.Register(context => context.Resolve<ISessionFactory>().OpenSession()) .As<ISession>() .InstancePerHttpRequest(); builder.RegisterGeneric(typeof(UserAccountService<>)).AsSelf(); builder.RegisterType(typeof(SamAuthenticationService<NhUserAccount>)) .AsSelf() .As(typeof(AuthenticationService<NhUserAccount>)); builder.RegisterGeneric(typeof(MembershipRebootConfiguration<>)).AsSelf(); builder.RegisterGeneric(typeof(NhRepository<>)).As(typeof(IRepository<>)); builder.RegisterGeneric(typeof(NhUserAccountRepository<>)).As(typeof(IUserAccountRepository<>)); builder.RegisterGeneric(typeof(NhGroupRepository<>)) .As(typeof(IGroupRepository<>)); builder.RegisterType(typeof(NhGroupRepository<NhGroup>)) .As(typeof(IGroupQuery)); builder.Register( context => new GroupService<NhGroup>("default", context.Resolve<IGroupRepository<NhGroup>>())).AsSelf(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
protected override void Load(ContainerBuilder builder) { builder.RegisterType<NHibernateQuery>(); builder.RegisterType<EntityDuplicateChecker>().As<IEntityDuplicateChecker>(); builder.RegisterGeneric(typeof(NHibernateRepository<>)).As(typeof(INHibernateRepository<>)); builder.RegisterGeneric(typeof(NHibernateRepositoryWithTypedId<,>)).As(typeof(INHibernateRepositoryWithTypedId<,>)); builder.RegisterType<DefaultSessionFactoryKeyProvider>().As<ISessionFactoryKeyProvider>(); }
protected override void Load(ContainerBuilder builder) { builder.RegisterGeneric(typeof (BasicNHibernateRepository<>)) .As(typeof (IRepository<>)); builder.RegisterGeneric(typeof(BasicNHibernateRepositoryWithGuid<>)) .As(typeof(IRepositoryWithGuid<>)); }
private static void SetGenerator(ContainerBuilder container) { container.RegisterType<Generator.Database.LiturgieDatabase>().As<ILiturgieDatabase.ILiturgieDatabase>(); container.RegisterType<Generator.LiturgieOplosser.LiturgieOplosser>().As<ILiturgieDatabase.ILiturgieLosOp>().WithParameter("defaultSetNameEmpty", Properties.Settings.Default.SetNameEmpty); container.RegisterGeneric(typeof(Generator.Database.FileSystem.FileEngine<>)).As(typeof(IDatabase.Engine.IEngine<>)); container.RegisterGeneric(typeof(Database.EngineManager<>)).As(typeof(IDatabase.IEngineManager<>)); SetMsPowerpointBuilder(container); }
private static void Register(ContainerBuilder builder) { //获取引用的程序集 var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList(); //装载仓储 builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); //装载服务 builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces(); //装载泛型基类 builder.RegisterGeneric(typeof(Domain.Repositories.Repository<,>)).As(typeof(Domain.Repositories.IRepository<,>)); builder.RegisterGeneric(typeof(Service<,>)).As(typeof(IService<,>)); // 装载控制器 builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterApiControllers(typeof(MvcApplication).Assembly); config = GlobalConfiguration.Configuration; builder.RegisterWebApiFilterProvider(config); #region Register modules builder.RegisterAssemblyModules(typeof(MvcApplication).Assembly); #endregion #region Model binder providers - excluded - not sure if need //builder.RegisterModelBinders(Assembly.GetExecutingAssembly()); //builder.RegisterModelBinderProvider(); #endregion #region Inject HTTP Abstractions /* The MVC Integration includes an Autofac module that will add HTTP request lifetime scoped registrations for the HTTP abstraction classes. The following abstract classes are included: -- HttpContextBase -- HttpRequestBase -- HttpResponseBase -- HttpServerUtilityBase -- HttpSessionStateBase -- HttpApplicationStateBase -- HttpBrowserCapabilitiesBase -- HttpCachePolicyBase -- VirtualPathProvider To use these abstractions add the AutofacWebTypesModule to the container using the standard RegisterModule method. */ builder.RegisterModule<AutofacWebTypesModule>(); #endregion }
protected override void Load(ContainerBuilder builder) { builder.Register(ctx => new MongoDbContext(_connectionString, _databaseName)) .AsSelf().InstancePerLifetimeScope(); builder.RegisterGeneric(typeof (BasicMongoRepository<>)) .As(typeof (IRepository<>)); builder.RegisterGeneric(typeof(BasicMongoRepositoryWithGuid<>)) .As(typeof(IRepositoryWithGuid<>)); }
public static ContainerBuilder GetBuilder(AppSettingConstant.DbFrameworkType dbFrameworkUse) { var builder = new ContainerBuilder(); var serviceAssembly = Assembly.Load("MyUniversity.Services"); builder.RegisterAssemblyTypes(serviceAssembly) .Where(x => x.Name.EndsWith("Service")) .AsImplementedInterfaces() .InstancePerLifetimeScope(); //builder.RegisterType<CourseService>().As<ICourseService>().InstancePerLifetimeScope(); //builder.RegisterType<DepartmentService>().As<IDepartmentService>().InstancePerLifetimeScope(); // Register for Repositories, UnitOfWork switch (dbFrameworkUse) { case AppSettingConstant.DbFrameworkType.Nhibernate: builder.RegisterGeneric(typeof(MyUniversity.Dal.Repositories.NHibernate.BaseRepository<,>)) .As(typeof(IBaseRepository<,>)) .InstancePerLifetimeScope(); builder.RegisterType<NHUnitOfWork>() .As<IUnitOfWork>() .InstancePerLifetimeScope(); builder.Register(x => DatabaseInitialization.GetNHibernateDbConfig() .BuildSessionFactory()).As<ISessionFactory>().SingleInstance(); builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).InstancePerLifetimeScope(); break; case AppSettingConstant.DbFrameworkType.EntityFramework: builder.RegisterGeneric(typeof(MyUniversity.Dal.Repositories.EntityFramework.BaseRepository<,>)) .As(typeof (IBaseRepository<,>)) .InstancePerLifetimeScope(); //builder.RegisterType<EFStudentProfileRepository>() // .As<IStudentProfileRepository>() // .InstancePerLifetimeScope(); ////builder.RegisterType<CourseRepository>() //// .As<ICourseRepository>() //// .InstancePerLifetimeScope(); //builder.RegisterType<DepartmentRepository>() // .As<IDepartmentRepository>() // .InstancePerLifetimeScope(); //builder.RegisterType<InstructorProfileRepository>() // .As<IInstructorProfileRepository>() // .InstancePerLifetimeScope(); //builder.RegisterType<EnrollmentRepository>() // .As<IEnrollmentRepository>() // .InstancePerLifetimeScope(); //builder.RegisterType<PersonRepository>() // .As<IPersonRepository>() // .InstancePerLifetimeScope(); builder.RegisterType<EFUnitOfWork>() .As<IUnitOfWork>() .InstancePerLifetimeScope(); builder.RegisterType<MyUniversityDbContext>().InstancePerLifetimeScope(); break; } return builder; }
protected override void Load(ContainerBuilder builder) { builder.RegisterInstance(_configuration).SingleInstance(); builder.RegisterGeneric(typeof (BasicRavenRepository<>)) .As(typeof(IRepository<>)) .InstancePerLifetimeScope(); builder.RegisterGeneric(typeof (BasicRavenRepositoryWithGuid<>)) //.As(typeof(IRepository<>)) .As(typeof (IRepositoryWithGuid<>)) .InstancePerLifetimeScope(); builder.RegisterGeneric(typeof (Refrence<>)) //.PropertiesAutowired() .AsSelf() .InstancePerDependency(); /* builder.RegisterGeneric(typeof(EventsRepository<>)) .As(typeof(IEventsRepository<>)); builder.RegisterType<UserProfileRavenRepository>() .As<IUserProfileRepository>(); builder.RegisterType<ObjectStrategyRepository>() .As<IObjectStrategyRepository>(); builder.RegisterType<ReportRepository>() .As<IReportRepository>(); builder.RegisterType<RegionStrategyRepository>() .As<IRegionStrategyRepository>(); builder.RegisterType<SensorsStrategyRepository>() .As<ISesnorsStrategyRepository>(); builder.RegisterType<ObjectsRepository>() .As<IObjectsRepository>(); builder.RegisterType<CategoryRepository>() .As<ICategoryRepository>(); builder.RegisterType<TicketsRepository>() .As<ITicketsRepository>(); builder.RegisterType<DCUStartTimesRepository>().As<IDCUStartTimesRepository>(); builder.RegisterType<SensorsRepository>() .As<ISensorsRepository>();*/ /* builder.RegisterAssemblyTypes(typeof(TrajectoryCoord).Assembly) .AssignableTo(typeof(IEventStreamStrategy<>)) .AsSelf() .AsImplementedInterfaces();*/ }
protected override void Load(ContainerBuilder b) { b.RegisterGeneric(typeof(EmitUoWInterfaceImplementor<>)) .AsSelf() .InstancePerLifetimeScope(); b.RegisterGeneric(typeof(EmitRawUoWInterfaceImplementor<>)) .AsSelf() .InstancePerLifetimeScope(); }
protected override void Load(ContainerBuilder builder) { builder.RegisterGeneric(typeof(GenericService<>)).As(typeof(IGenericService<>)); builder.RegisterGeneric(typeof(ParametersService<>)).As(typeof(IParametersService<>)); builder.RegisterType<PluginService>().As<IPluginService>() .WithParameter("webSiteRoot", HttpContext.Current.Server.MapPath("~/")); builder.RegisterType<RunConfigurationService>().As<IRunConfigurationService>(); base.Load(builder); }
public void Configure(IComponentRegistry componentRegistry) { // Ideally all these registrations should not exist, but currently generics are not properly auto-registered // by Orchard, see: https://github.com/OrchardCMS/Orchard/issues/1968 var builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(SqlConnectionManager<>)).As(typeof(ISqlConnectionManager<>)); builder.RegisterGeneric(typeof(GraphServicesFactory<,,,>)).As(typeof(IGraphServicesFactory<,,,>)).InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(QueryableGraph<>)).As(typeof(IQueryableGraph<>)); builder.Update(componentRegistry); }
private void SetDependencyResolver() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterGeneric(typeof(EventsDispatcher<>)) .SingleInstance() .PropertiesAutowired(); builder.RegisterGeneric(typeof(MemoryBuffer<>)).As(typeof(IEventsBuffer<>)) .SingleInstance(); DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build())); }
private static void SetAutofacContainer() { var configuration = (HttpConfiguration) GlobalConfiguration.Configuration; var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterGeneric(typeof (UnitOfWork<>)).As(typeof (IUnitOfWork<>)); builder.RegisterGeneric(typeof (RepositoryBase<>)).As(typeof (IRepository<>)); builder.RegisterType(typeof (CategoryService)).As(typeof (ICategoryService)).InstancePerDependency(); builder.RegisterType(typeof (DepartmentService)).As(typeof (IDepartmentService)).InstancePerDependency(); var container = builder.Build(); var resolver = new AutofacWebApiDependencyResolver(container); configuration.DependencyResolver = resolver; }
protected override void Load(ContainerBuilder builder) { builder.RegisterAssemblyTypes(ThisAssembly) .AsNamedClosedTypesOf(typeof(IRequestHandler<,>), t => "request_handler"); builder.RegisterGeneric(typeof(GetDraftDataHandler<>)) .Named("request_handler", typeof(IRequestHandler<,>)); builder.RegisterGeneric(typeof(SetDraftDataHandler<>)) .Named("request_handler", typeof(IRequestHandler<,>)); // Order matters here builder.RegisterGenericDecorators(ThisAssembly, typeof(IRequestHandler<,>), "request_handler", typeof(EventDispatcherRequestHandlerDecorator<,>), // <-- inner most decorator typeof(RequestAuthorizationDecorator<,>), typeof(NotificationReadOnlyAuthorizeDecorator<,>)); // <-- outer most decorator // Register the map classes builder.RegisterAssemblyTypes(ThisAssembly) .Where(t => t.Namespace != null && t.Namespace.Contains("Mappings")) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(ThisAssembly) .AsClosedTypesOf(typeof(IEventHandler<>)) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(ThisAssembly) .Where(t => t.IsAssignableTo<FluentValidation.IValidator>()) .AsImplementedInterfaces(); // Register all components with the AutoRegister attribute as self and interfaces builder.RegisterAssemblyTypes(ThisAssembly, typeof(NotificationApplication).Assembly) .Where(t => t.GetCustomAttribute<AutoRegisterAttribute>() != null) .AsSelf() .AsImplementedInterfaces(); if (HasAsposeLicense()) { builder.RegisterType<AsposePdfGenerator>().As<IPdfGenerator>(); } builder.RegisterType<InMemoryAuthorizationManager>().As<IAuthorizationManager>(); builder.RegisterType<RequestAuthorizationAttributeCache>().AsSelf().SingleInstance(); builder.RegisterType<AddressBuilder>().InstancePerDependency().AsSelf(); // Rules builder.RegisterAssemblyTypes(ThisAssembly) .AssignableTo<IMovementRule>() .As<IMovementRule>(); }
protected override void Load(ContainerBuilder builder) { Mapper.CreateMap<XSeverityLevel, SeverityLevel>(); builder.Register( _ => new DocumentClient(new Uri(_.Resolve<IConfig>()["DocumentDatabaseUri"]), _.Resolve<IConfig>()["DocumentDatabaseAuth"])).SingleInstance(); builder.RegisterType<DocumentConnection>().As<IDocumentConnection>().SingleInstance(); builder.RegisterType<DocumentEntityCache>().As<IDocumentEntityCache>(); builder.RegisterGeneric(typeof (DocumentRepo<>)).As(typeof (IDocumentRepo<>)).InstancePerLifetimeScope(); builder.Register(_ => CloudStorageAccount.Parse(_.Resolve<IConfig>()["StorageConnectionString"])) .AsSelf() .InstancePerRequest(); builder.Register(_ => _.Resolve<CloudStorageAccount>().CreateCloudTableClient()) .AsSelf() .InstancePerRequest(); builder.Register(_ => _.Resolve<CloudStorageAccount>().CreateCloudBlobClient()) .AsSelf() .InstancePerRequest(); builder.Register(_ => _.Resolve<CloudStorageAccount>().CreateCloudQueueClient()) .AsSelf() .InstancePerRequest(); builder.RegisterGeneric(typeof(QueueMessageRepo<>)).As(typeof(IQueueMessageRepo<>)).InstancePerRequest(); builder.RegisterType<RedisConnection>().As<IRedisConnection>().SingleInstance(); builder.Register(_ => _.Resolve<IRedisConnection>().GetDatabase()).As<IDatabase>(); builder.Register(_ => _.Resolve<IRedisConnection>().GetSubscriber()).As<ISubscriber>(); builder.RegisterType<RedisEntityCache>().As<IRedisEntityCache>(); builder.RegisterType<RedisMemoryCache>().As<IMemoryCache>(); builder.RegisterType<RedisMemoryCache>().As<IRedisMemoryCache>(); builder.RegisterType<BlobRepo>().As<IBlobRepo>().InstancePerRequest(); builder.RegisterType<BlobRepoFactory>().As<IBlobRepoFactory>().InstancePerRequest(); builder.RegisterType<BlobStorageFileRepo>().As<IStorageFileRepo>().InstancePerRequest(); builder.RegisterType<LogService>().As<ILogService>().InstancePerRequest(); }
protected override void Load(Autofac.ContainerBuilder builder) { builder.RegisterAssemblyTypes(typeof(MediatR.IMediator).GetTypeInfo().Assembly) .AsImplementedInterfaces(); builder.Register <ServiceFactory>(context => { var componentContext = context.Resolve <IComponentContext>(); return(t => componentContext.TryResolve(t, out var o) ? o : null); }); builder.RegisterGeneric(typeof(CrocusoftProje.Infrastructure.Behaviors.LoggingBehavior <,>)).As(typeof(IPipelineBehavior <,>)); builder.RegisterGeneric(typeof(CrocusoftProje.Infrastructure.Behaviors.ValidatorBehavior <,>)).As(typeof(IPipelineBehavior <,>)); }
protected override void Load(ContainerBuilder builder) { InitializeSessionFactories(); builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); builder.RegisterGeneric(typeof(TransactionalRepository<>)).As(typeof(ITransactionalRepository<>)); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AsImplementedInterfaces(); builder.Register(x => NHibernateSessionManager .SessionFactories .First(factory => !factory.WriteOnly).GetSession() ).As<ISession>(); builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource()); }
/// <summary> /// Register types that are shared amongst all containers. /// </summary> /// <param name="builder"> /// The builder. /// </param> private static void RegisterEssentials(ContainerBuilder builder) { builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IRepository<>)); builder.RegisterGeneric(typeof(CrudService<>)).As(typeof(ICrudService<>)); // Assembly scanning builder.RegisterAssemblyTypes(Assembly.Load("DnD.DataLayer")) .Where(t => t.Name.EndsWith("Repository") && !t.Name.StartsWith("BaseRe")) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(Assembly.Load("DnD.Service")) .Where(t => t.Name.EndsWith("Service") && !t.Name.StartsWith("CrudSer")) .AsImplementedInterfaces(); }
protected override void Load(ContainerBuilder moduleBuilder) { moduleBuilder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,,,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,,,,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,,,,,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,,,,,,,>)).AsSelf(); moduleBuilder.RegisterGeneric(typeof(DisposableTuple<,,,,,,,,,,>)).AsSelf(); }
private static void SetupExtensibility(Autofac.ContainerBuilder builder) { var dynamicProxy = new CastleDynamicProxyProvider(); var aopRepository = new AspectRepository(dynamicProxy); var dllPlugins = (from key in ConfigurationManager.AppSettings.AllKeys where key.StartsWith("PluginsPath", StringComparison.OrdinalIgnoreCase) let path = ConfigurationManager.AppSettings[key] let pathRelative = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path) let chosenPath = Directory.Exists(pathRelative) ? pathRelative : path select chosenPath) .ToList(); builder.RegisterInstance(new PluginsConfiguration { Directories = dllPlugins }); builder.RegisterType <SystemInitialization>(); builder.RegisterType <AutofacObjectFactory>().As <IObjectFactory>().SingleInstance(); builder.RegisterType <AutofacMefProvider>().As <IExtensibilityProvider>().SingleInstance(); builder.RegisterGeneric(typeof(PluginRepository <>)).As(typeof(IPluginRepository <>)).SingleInstance(); builder.RegisterInstance(aopRepository).As <IAspectRegistrator, IAspectComposer, IInterceptorRegistrator>(); builder.RegisterInstance(dynamicProxy).As <IMixinProvider, IDynamicProxyProvider>(); if (ConfigurationManager.AppSettings["Revenj.AllowAspects"] == "true") { builder.RegisterModule(new AspectsModule(aopRepository)); } }
private static void SetupExtensibility(Autofac.ContainerBuilder builder, bool withAspects) { var dynamicProxy = new CastleDynamicProxyProvider(); var aopRepository = new AspectRepository(dynamicProxy); var assemblies = NGS.Utility.AssemblyScanner.GetAssemblies().Where(it => it.FullName.StartsWith("NGS.")); builder.RegisterInstance(new PluginsConfiguration { Assemblies = assemblies }); builder.RegisterType <SystemInitialization>(); builder.RegisterType <AutofacObjectFactory>().As <IObjectFactory>().SingleInstance(); builder.RegisterType <AutofacMefProvider>().As <IExtensibilityProvider>().SingleInstance(); builder.RegisterGeneric(typeof(PluginRepository <>)).As(typeof(IPluginRepository <>)).SingleInstance(); builder.RegisterInstance(aopRepository).As <IAspectRegistrator, IAspectComposer, IInterceptorRegistrator>(); builder.RegisterInstance(dynamicProxy).As <IMixinProvider, IDynamicProxyProvider>(); if (withAspects) { var autofacModules = from type in NGS.Utility.AssemblyScanner.GetAllTypes() where type.IsPublic && typeof(Autofac.Module).IsAssignableFrom(type) && type.GetConstructor(new Type[0]) != null select type; foreach (var m in autofacModules) { builder.RegisterModule((Autofac.Module)Activator.CreateInstance(m)); } builder.RegisterModule(new AspectsModule(aopRepository)); } }
public IContainer CreateContainer() { var builder = new Autofac.ContainerBuilder(); builder.RegisterType<MyCommandHandler>().As<ICommandHandler<AnotherCommand>>(); builder.RegisterType<MyCommandHandler>().As<ICommandHandler<MyCommand>>(); builder.RegisterGeneric(typeof(CompositeCommandHandler<>)).As(typeof(ICommandHandler<>)); return builder.Build(); }
/// <summary> /// 注册泛型 /// 【RegisterGeneric】 /// </summary> /// <param name="builder"></param> /// <returns></returns> protected override Autofac.ContainerBuilder RegisterFunc(Autofac.ContainerBuilder builder) { builder.RegisterGeneric(typeof(BaseRepository <>)) .As(typeof(IBaseRepository <>)); builder.RegisterType <BookAppService>() .As <IBookService>(); return(builder); }
protected void Application_Start(object sender, EventArgs e) { System.Web.Mvc.AreaRegistration.RegisterAllAreas(); //mvc相关 System.Web.Routing.RouteTable.Routes.MapRoute("l2", "{controller}/{action}", defaults: new { controller = "Home", action = "Index" }); //ioc和aop相关 Type flagIScoped = typeof(IScoped); Type flagISingleton = typeof(ISingleton); Type flagITransient = typeof(ITransient); //bin目录下的所有的类型 var lstType = System.Web.Compilation.BuildManager.GetReferencedAssemblies() .Cast <System.Reflection.Assembly>() .SelectMany(x => x.GetTypes()) .ToList(); var lstTypeIScoped = lstType.Where(x => flagIScoped.IsAssignableFrom(x)) .Where(x => x != flagIScoped).ToArray(); var lstTypeISingleton = lstType.Where(x => flagISingleton.IsAssignableFrom(x)) .Where(x => x != flagISingleton).ToArray(); var lstTypeITransient = lstType.Where(x => flagITransient.IsAssignableFrom(x)) .Where(x => x != flagITransient).ToArray(); var builder = new Autofac.ContainerBuilder(); builder.RegisterTypes(lstTypeIScoped).AsSelf().AsImplementedInterfaces() .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies) .InstancePerRequest(); builder.RegisterTypes(lstTypeISingleton).AsSelf().AsImplementedInterfaces() .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies) .SingleInstance(); builder.RegisterTypes(lstTypeITransient).AsSelf().AsImplementedInterfaces() .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies) .InstancePerDependency(); builder.RegisterGeneric(typeof(Azeroth.Util.Log <>)) .As(typeof(Azeroth.Util.ILog <>)) .SingleInstance(); builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly()) .AsSelf() .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies) .InstancePerRequest() .EnableClassInterceptors() .InterceptedBy(typeof(App_Start.InterceptedHandler)); var container = builder.Build(); var resolver = new Autofac.Integration.Mvc.AutofacDependencyResolver(container); System.Web.Mvc.DependencyResolver.SetResolver(resolver); //日志信息相关的处理 this.LogConfigure(new Bll.Log(new Model.Entity.DbContext())); }
private static void SetupPatterns(Autofac.ContainerBuilder builder) { var serverModels = (from asm in NGS.Utility.AssemblyScanner.GetAssemblies() let type = asm.GetType("SystemBoot.Configuration") where type != null && type.GetMethod("Initialize") != null select asm) .ToList(); builder.RegisterGeneratedFactory <NGS.DomainPatterns.DomainModel.Factory>(); builder.RegisterType <NGS.DomainPatterns.DomainModel>(); builder.Register(c => c.Resolve <NGS.DomainPatterns.DomainModel.Factory>()(serverModels)).As <IDomainModel>().SingleInstance(); builder.RegisterType <DomainTypeResolver>().As <ITypeResolver>().SingleInstance(); builder.RegisterType <ServiceLocator>().As <IServiceLocator, IServiceProvider>().InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(WeakCache <>)).As(typeof(IDataCache <>)).InstancePerLifetimeScope(); builder.RegisterType <DomainEventSource>().As <IDomainEventSource>().InstancePerLifetimeScope(); builder.RegisterType <DomainEventStore>().As <IDomainEventStore>().InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(SingleDomainEventSource <>)).As(typeof(IDomainEventSource <>)).InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(RegisterChangeNotifications <>)).As(typeof(IObservable <>)).SingleInstance(); builder.RegisterType <DataContext>().As <IDataContext>().InstancePerLifetimeScope(); }
protected override void Load(AutofacRef.ContainerBuilder builder) { var executingAssembly = Reflaction.Assembly.Load(nameof(BusinessLayer)); //Register all custom stores builder.RegisterAssemblyTypes(executingAssembly) .Where(x => x.Name.EndsWith("Store")).AsImplementedInterfaces().InstancePerLifetimeScope(); //Register custom UserManagers builder.RegisterGeneric(typeof(CustomUserManager <>)).AsSelf().InstancePerLifetimeScope(); //Register custom RoleManagers builder.RegisterGeneric(typeof(CustomRoleManager <>)).AsSelf().InstancePerLifetimeScope(); //builder.RegisterAssemblyTypes(executingAssembly) // .Where(x => x.BaseType != null && x.BaseType.IsGenericType // && x.BaseType.GetGenericTypeDefinition() == typeof(UserManager<>).GetGenericTypeDefinition()).AsSelf().InstancePerLifetimeScope(); //To exclude types from scanning, use the Except() predicate: //builder.RegisterAssemblyTypes(asm).Except<MyUnwantedType>(); }
private static void SetupPatterns(Autofac.ContainerBuilder builder) { var serverModels = (from key in ConfigurationManager.AppSettings.AllKeys where key.StartsWith("ServerAssembly", StringComparison.OrdinalIgnoreCase) select LoadAssembly(ConfigurationManager.AppSettings[key])) .ToList(); if (serverModels.Count == 0) { serverModels = (from asm in NGS.Utility.AssemblyScanner.GetAssemblies() let type = asm.GetType("SystemBoot.Configuration") where type != null && type.GetMethod("Initialize") != null select asm) .ToList(); if (serverModels.Count == 0) { throw new ConfigurationErrorsException(@"Server assemblies not found. When running in compiled mode, server assemblies must be deployed with other assemblies. Alternatively, explicitly specify sever assembly in the config file. Example: <add key=""ServerAssembly_Domain"" value=""AppDomainModel.dll"" />"); } } builder.RegisterGeneratedFactory <NGS.DomainPatterns.DomainModel.Factory>(); builder.RegisterType <NGS.DomainPatterns.DomainModel>(); builder.Register(c => c.Resolve <NGS.DomainPatterns.DomainModel.Factory>()(serverModels)).As <IDomainModel>().SingleInstance(); builder.RegisterType <DomainTypeResolver>().As <ITypeResolver>().SingleInstance(); builder.RegisterType <ServiceLocator>().As <IServiceLocator, IServiceProvider>().InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(WeakCache <>)).As(typeof(IDataCache <>)).InstancePerLifetimeScope(); builder.RegisterType <DomainEventSource>().As <IDomainEventSource>().InstancePerLifetimeScope(); builder.RegisterType <DomainEventStore>().As <IDomainEventStore>().InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(SingleDomainEventSource <>)).As(typeof(IDomainEventSource <>)).InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(RegisterChangeNotifications <>)).As(typeof(IObservable <>)).SingleInstance(); builder.RegisterType <DataContext>().As <IDataContext>().InstancePerLifetimeScope(); }
/// <summary> /// 扫描程序集注册 /// 【RegisterAssemblyTypes】 /// </summary> /// <param name="builder"></param> /// <returns></returns> protected override Autofac.ContainerBuilder RegisterFunc(Autofac.ContainerBuilder builder) { Assembly[] assemblies = ReflectionHelper.GetAllAssemblies(); builder.RegisterAssemblyTypes(assemblies) .Where(cc => cc.Name.EndsWith("Repository") | //筛选程序集内所有具象类(concrete classes) cc.Name.EndsWith("Service")) .Where(cc => cc.IsClass) //只要class型(主要为了排除值和interface类型) .PublicOnly() //只要public访问权限的 .Except <TeacherRepository>() //排除某类型 //.As(x => x.GetInterfaces()[0])//反射出其实现的接口,默认以第一个接口类型暴露 .AsImplementedInterfaces(); //自动以其实现的所有接口类型暴露(包括IDisposable接口) builder.RegisterGeneric(typeof(BaseRepository <>)) .As(typeof(IBaseRepository <>)); return(builder); }
public void Register(Autofac.ContainerBuilder builder, Nop.Core.Infrastructure.ITypeFinder typeFinder) {//HTTP context and other related stuff //builder.Register(c => // //register FakeHttpContext when HttpContext is not available // HttpContext.Current != null ? // (new HttpContextWrapper(HttpContext.Current) as HttpContextBase) : // (new FakeHttpContext("~/") as HttpContextBase)) // .As<HttpContextBase>() // .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Request) .As <HttpRequestBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Response) .As <HttpResponseBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Server) .As <HttpServerUtilityBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Session) .As <HttpSessionStateBase>() .InstancePerLifetimeScope(); //每次依赖都使用一个新的数据库对象 builder.Register <IDbContext>(c => new NopObjectContext()).InstancePerDependency(); //注册工作单元 builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerDependency(); //注册泛型仓储 builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope(); //注册服务 builder.RegisterType <Nop.Services.Users.UserService>().As <Nop.Services.Users.IUserService>().InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .Where(t => !t.IsAbstract && typeof(ApiController).IsAssignableFrom(t)) .InstancePerMatchingLifetimeScope(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces(); }
public static Autofac.ContainerBuilder AddRepositories(this Autofac.ContainerBuilder builder) { Assembly appServiceAssembly = Assembly.GetExecutingAssembly(); /** 如果是Core,不可以使用使用Autofac的InstancePerRequest,否则会报异常 * 可以换成InstancePerLifetimeScope,相当于Core的Scoped */ builder.RegisterType <MyDbContext>() .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(appServiceAssembly) .Where(cc => cc.Name.EndsWith("Repository")) //筛选具象类(concrete classes) .PublicOnly() //只要public访问权限的 .Where(cc => cc.IsClass) //只要class型(主要为了排除值和interface类型) .AsImplementedInterfaces(); //自动以其实现的所有接口类型暴露(包括IDisposable接口) //注册泛型仓储 builder.RegisterGeneric(typeof(BaseRepository <>)) .As(typeof(IBaseRepository <>)); return(builder); }
protected override void Load(Autofac.ContainerBuilder builder) { #region 带有接口的服务注册 #region AOP List <Type> aopList = new List <Type>(); if (Appsettings.App(new string[] { "AppSettings", "RedisCacheAOP", "Enabled" }).ObjToBool()) { builder.RegisterType <RedisCacheManager>().As(typeof(IRedisCacheManager)).SingleInstance(); builder.RegisterType <BlogRedisCacheAOP>(); aopList.Add(typeof(BlogRedisCacheAOP)); } if (Appsettings.App(new string[] { "AppSettings", "MemoryCacheAOP", "Enabled" }).ObjToBool()) { builder.RegisterType <Microsoft.Extensions.Caching.Memory.MemoryCache>().As(typeof(IMemoryCache)).SingleInstance(); builder.RegisterType <Helper.MemoryCache>().As(typeof(ICache)).SingleInstance(); builder.RegisterType <BlogCacheAOP>(); aopList.Add(typeof(BlogCacheAOP)); } if (Appsettings.App(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool()) { builder.RegisterType <BlogLogAOP>(); aopList.Add(typeof(BlogLogAOP)); } #endregion // 注册泛型仓储 builder.RegisterGeneric(typeof(BaseRepository <>)).As(typeof(IBaseRepository <>)).InstancePerDependency(); // 注册服务 builder.RegisterType <AdvertisementService>().As <IAdvertisementService>() .InstancePerLifetimeScope() .EnableInterfaceInterceptors() .InterceptedBy(aopList.ToArray()); builder.RegisterType <BlogArticleService>().As <IBlogArticleService>() .InstancePerLifetimeScope() .EnableInterfaceInterceptors() .InterceptedBy(aopList.ToArray()); #endregion }
public void Register(Autofac.ContainerBuilder builder, Core.Infrastructure.TypeFinders.ITypeFinder typeFinder) { #region 数据库 const string MAIN_DB = "OrderingSystem"; builder.Register(c => new OrderingSystemDbContext(MAIN_DB)) .As <IDbContext>() .Named <IDbContext>(MAIN_DB) .SingleInstance(); builder.RegisterGeneric(typeof(EfRepository <>)) .As(typeof(IRepository <>)) .WithParameter(ResolvedParameter.ForNamed <IDbContext>(MAIN_DB)) .SingleInstance(); #endregion builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(IUserBusiness))).AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof(UserService).Assembly) .AsImplementedInterfaces() .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces(); }
RegisterGeneric(this ContainerBuilder builder, Func <IComponentContext, Type[], object> factory) { return(builder.RegisterGeneric((ctxt, types, parameters) => factory(ctxt, types))); }
public static void AddTestLogging(this ContainerBuilder builder) { builder.RegisterGeneric(typeof(Logger <>)).As(typeof(ILogger <>)); builder.RegisterType <NullLoggerFactory>().AsImplementedInterfaces().InstancePerLifetimeScope(); }
public static void Register() { //初始化AutoFac的相关功能 /* * 1.0 告诉AutoFac初始化数据仓储层FB.CMS.Repository.dll中所有类的对象实例。这些对象实例以其接口的形式保存在AutoFac容器中 * 2.0 告诉AutoFac初始化业务逻辑层FB.CMS.Services.dll中所有类的对象实例。这些对象实例以其接口的形式保存在AutoFac容器中 * 3.0 将MVC默认的控制器工厂替换成AutoFac的工厂 */ //第一步: 构造一个AutoFac的builder容器 ContainerBuilder builder = new Autofac.ContainerBuilder(); //第二步:告诉AutoFac控制器工厂,控制器类的创建去哪些程序集中查找(默认控制器工厂是去扫描bin目录下的所有程序集) //2.1 从当前运行的bin目录下加载Pro.Web.dll程序集 Assembly controllerAss = Assembly.Load("Pro.Web"); //2.2 告诉AutoFac控制器工厂,控制器的创建从controllerAss中查找(注意:RegisterControllers()方法是一个可变参数,如果你的控制器类的创建需要去多个程序集中查找的话,那么我们就再用Assembly controllerBss=Assembly.Load("需要的程序集名")加载需要的程序集,然后与controllerAss组成数组,然后将这个数组传递到RegisterControllers()方法中) builder.RegisterControllers(controllerAss); //第三步:告诉AutoFac容器,创建项目中的指定类的对象实例,以接口的形式存储(其实就是创建数据仓储层与业务逻辑层这两个程序集中所有类的对象实例,然后以其接口的形式保存到AutoFac容器内存中,当然如果有需要也可以创建其他程序集的所有类的对象实例,这个只需要我们指定就可以了) //3.1 加载数据仓储层Pro.Repository这个程序集。 Assembly repositoryAss = Assembly.Load("Pro.Repository"); //3.2 反射扫描这个Pro.Repository.dll程序集中所有的类,得到这个程序集中所有类的集合。 Type[] rtypes = repositoryAss.GetTypes(); //3.3 告诉AutoFac容器,创建rtypes这个集合中所有类的对象实例 builder.RegisterTypes(rtypes).AsImplementedInterfaces(); //指明创建的rtypes这个集合中所有类的对象实例,以其接口的形式保存 //3.4 加载数据访问层Pro.Dal这个程序集。 Assembly servicesAss = Assembly.Load("Pro.Dal"); ////3.5 反射扫描这个Pro.Dal.dll程序集中所有的类,得到这个程序集中所有类的集合。 Type[] stypes = servicesAss.GetTypes(); ////3.6 告诉AutoFac容器,创建stypes这个集合中所有类的对象实例 builder.RegisterTypes(stypes).AsImplementedInterfaces(); //指明创建的stypes这个集合中所有类的对象实例,以其接口的形式保存 builder.RegisterGeneric(typeof(DataRepository <>)).As(typeof(IDataRepository <>)) .InstancePerDependency(); builder.RegisterGeneric(typeof(BaseService <>)).As(typeof(IBaseService <>)) .InstancePerDependency(); //第四步:创建一个真正的AutoFac的工作容器 var container = builder.Build(); //我们已经创建了指定程序集的所有类的对象实例,并以其接口的形式保存在AutoFac容器内存中了。那么我们怎么去拿它呢? //从AutoFac容器内部根据指定的接口获取其实现类的对象实例 //假设我要拿到IsysFunctionServices这个接口的实现类的对象实例,怎么拿呢? //var obj = container.Resolve<IsysFunctionServices>(); //只有有特殊需求的时候可以通过这样的形式来拿。一般情况下没有必要这样来拿,因为AutoFac会自动工作(即:会自动去类的带参数的构造函数中找与容器中key一致的参数类型,并将对象注入到类中,其实就是将对象赋值给构造函数的参数) //第五步:将当前容器中的控制器工厂替换掉MVC默认的控制器工厂。(即:不要MVC默认的控制器工厂了,用AutoFac容器中的控制器工厂替代)此处使用的是将AutoFac工作容器交给MVC底层 (需要using System.Web.Mvc;) DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //我们知道控制器的创建是调用MVC默认的控制器工厂,默认的控制器工厂是调用控制器类的无参构造函数 //可是我们如果要使用AutoFac自动工厂,将对象通过构造函数注入类中,那么这个构造函数就需要带参数 //如果我们将控制器的无参构造函数删除,保留带参数的构造函数,MVC默认的控制器工厂来创建控制的时候 //就会去调用无参的构造函数,可是这时候发现没有无参的构造函数于是就报“没有为该对象定义无参数的构造函数”错误 //既然报错,那我们如果保留无参的构造函数,同时在声明一个带参数的构造函数是否可行呢? //答案;行是行,但是创建控制器的时候,MVC默认的控制器工厂调用的是无参构造函数,它并不会去调用有参的构造函数 //这时候,我们就只能将AutoFac它的控制器工厂替换调用MVC默认的控制器工厂(控制器由AutoFac的控制器工厂来创建) //而AutoFac控制器工厂在创建控制的时候只会扫描带参数的构造函数,并将对象注入到带参数的构造函数中 //AutofacDependencyResolver这个控制器工厂是继承了 IDependencyResolver接口的,而IDependencyResolver接口是MVC的东西 //MVC默认的控制器工厂名字叫:DefaultControllerFactory //具体参考:http://www.cnblogs.com/artech/archive/2012/04/01/controller-activation-032.html }
private void RegisterLogging(Autofac.ContainerBuilder builder) { builder.RegisterInstance(this.LoggerFactory).As <ILoggerFactory>().SingleInstance(); builder.RegisterGeneric(typeof(Logger <>)).As(typeof(ILogger <>)).SingleInstance(); }
private void RegisterInternal(Type serviceType, Type implementerType, IOC.LifetimeScopeType lifetimeScope, string name = null) { if (implementerType.IsOpenGeneric()) { var registration = _builder .RegisterGeneric(implementerType); if (string.IsNullOrEmpty(name)) { registration .As(serviceType); } else { registration .Named(name, serviceType); } switch (lifetimeScope) { case IOC.LifetimeScopeType.SingleInstance: registration.SingleInstance(); break; case IOC.LifetimeScopeType.InstancePerLifetimeScope: registration.InstancePerLifetimeScope(); break; case IOC.LifetimeScopeType.InstancePerRequest: registration.InstancePerRequest(); break; case IOC.LifetimeScopeType.InstancePerDependency: default: registration.InstancePerDependency(); break; } } else { var registration = _builder .RegisterType(implementerType); if (string.IsNullOrEmpty(name)) { registration .As(serviceType); } else { registration .Named(name, serviceType); } switch (lifetimeScope) { case IOC.LifetimeScopeType.SingleInstance: registration.SingleInstance(); break; case IOC.LifetimeScopeType.InstancePerLifetimeScope: registration.InstancePerLifetimeScope(); break; case IOC.LifetimeScopeType.InstancePerRequest: registration.InstancePerRequest(); break; case IOC.LifetimeScopeType.InstancePerDependency: default: registration.InstancePerDependency(); break; } } }
protected override void Load(ContainerBuilder builder) { Contract.Requires(builder != null); builder.RegisterGeneric(typeof(PluginsMetadataCache<>)).SingleInstance(); builder.RegisterGeneric(typeof(PluginsContainer<>)).As(typeof(IPluginsContainer<>)).InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(NamedPlugins<>)).As(typeof(INamedPlugins<>)).InstancePerLifetimeScope(); Plugins.FindAndRegisterModules(builder); base.Load(builder); }