public Update ( IComponentRegistry componentRegistry ) : void | ||
componentRegistry | IComponentRegistry | |
Результат | void |
public static Autofac.IContainer Strap() { OnProgressChanged(0, @"Start bootstraping..."); if (_builder.IsNull()) { _builder = new ContainerBuilder(); _builder.RegisterModule(new InfrastructureModule(25000, new[] { @"Server=127.0.0.1;Database=macsauto2;User Id=root;Password=root", @"Server=codebrosdb.c7n7mt4zucyl.ap-southeast-1.rds.amazonaws.com;User Id=codebros;Password=codebros" })); _builder.RegisterModule(new InfrastructureCrosscuttingModule()); _builder.RegisterModule(new PresentationModule()); _container = _container ?? _builder.Build(); _builder = new ContainerBuilder(); _builder.RegisterInstance(_container).As<Autofac.IContainer>(); _builder.Update(_container); _strapped = true; } OnProgressChanged(20, @"Done registering modules.."); return _container; }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); var documentStore = new DocumentStore { Url = "http://localhost:8080/databases/CQRSSimpleExample" }; documentStore.Initialize(); IndexCreation.CreateIndexes(typeof(UserByName).Assembly, documentStore); var builder = new ContainerBuilder(); builder.RegisterInstance(documentStore).As<IDocumentStore>(); //builder.RegisterType<UserHandler>().AsSelf(); builder.RegisterGeneric(typeof (Repository<>)).As(typeof (IRepository<>)); builder.RegisterType<UserQueries>().AsSelf(); builder.Register(t => documentStore.OpenSession()).As<IDocumentSession>(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); var bus = new SimpleBus(container.Resolve); builder = new ContainerBuilder(); builder.RegisterInstance(bus).AsImplementedInterfaces(); builder.Update(container); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
/// <summary> /// Configures a <see cref="NDomain.IoC.IDependencyResolver"/> to use Autofac /// based on the <paramref name="container"/>. Useful to resolve application message handlers /// that depend on other components external to NDomain. /// The application's Autofac container will also get updated with registries for NDomain's components. /// </summary> /// <param name="b">configurator instance</param> /// <param name="container">application's Autofac container</param> /// <returns>Current configurator instance, to be used in a fluent manner.</returns> public static IoCConfigurator WithAutofac(this IoCConfigurator b, IContainer container) { b.Resolver = new AutofacDependencyResolver(container.BeginLifetimeScope()); b.Configured += context => { var builder = new ContainerBuilder(); builder.RegisterInstance(context); builder.RegisterInstance(context.CommandBus); builder.RegisterInstance(context.EventBus); builder.RegisterInstance(context.EventStore).As<IEventStore>(); builder.RegisterGeneric(typeof(AggregateRepository<>)) .As(typeof(IAggregateRepository<>)).SingleInstance(); // usually command/event handlers foreach (var knownType in b.KnownTypes) { builder.RegisterType(knownType) .AsSelf() .PreserveExistingDefaults(); } builder.Update(container); }; return b; }
public static void ResolveAutofacDependencies(this object obj) { // Bootstrap if (Container == null) { Container = new Bootstrapper().Bootstrap(); } if (obj is Page) { var builder = new ContainerBuilder(); builder.RegisterInstance(obj).As<Page>(); builder.Update(Container); } PropertyInfo[] properties = obj.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); using (var lifetimeScope = Container.BeginLifetimeScope()) { foreach (var property in properties.Where(p => p.GetCustomAttributes(typeof(InjectAttribute), false).Any())) { object instance = null; if (!lifetimeScope.TryResolve(property.PropertyType, out instance)) { throw new InvalidOperationException("Could not resolve type " + property.PropertyType); } property.SetValue(obj, instance); } } }
public static void InitContainer() { var builder = new ContainerBuilder(); var container = builder.Build(); var typefinder = new WebAppDomainTypeFinder(); builder = new ContainerBuilder(); builder.RegisterInstance(typefinder).As<ITypeFinder>().SingleInstance(); builder.Update(container); builder = new ContainerBuilder(); var drtypes = typefinder.FindClassesOfType<IDependencyRegistrar>(); var drInstances = new List<IDependencyRegistrar>(); foreach (var drtype in drtypes) { drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drtype)); } foreach (var dr in drInstances) { dr.Register(builder,typefinder); } builder.Update(container); //将Autofac容器中的实例注册到mvc自带的容器中 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); ContainerManager.RegisterContainer(container); }
public static void UseStardustManager(this IAppBuilder appBuilder, ManagerConfiguration managerConfiguration, ILifetimeScope lifetimeScope) { appBuilder.Map( managerConfiguration.Route, inner => { var config = new HttpConfiguration { DependencyResolver = new AutofacWebApiDependencyResolver(lifetimeScope) }; config.MapHttpAttributeRoutes(); config.Services.Add(typeof (IExceptionLogger), new GlobalExceptionLogger()); inner.UseAutofacWebApi(config); inner.UseWebApi(config); }); var builder = new ContainerBuilder(); builder.RegisterModule(new ManagerModule(managerConfiguration)); builder.Update(lifetimeScope.ComponentRegistry); //to start the timers etc lifetimeScope.Resolve<ManagerController>(); }
private static void RegisterOperations() { var newBuilder = new ContainerBuilder(); newBuilder.Register(x => Startup.Container.GetInstance<ISolrOperations<Post>>()); newBuilder.Register(x => Startup.Container.GetInstance<ISolrConnection>()); newBuilder.Update(Big.Box); }
public void Configuration(IAppBuilder app) { // Call our IoC static helper method to start the typical Autofac SignalR setup var container = IocConfig.RegisterDependencies(); // Get your HubConfiguration. In OWIN, we create one rather than using GlobalHost var hubConfig = new HubConfiguration(); // Sets the dependency resolver to be autofac. hubConfig.Resolver = new AutofacDependencyResolver(container); // OWIN SIGNALR SETUP: // Register the Autofac middleware FIRST, then the standard SignalR middleware. app.UseAutofacMiddleware(container); app.MapSignalR("/signalr", hubConfig); // There's not a lot of documentation or discussion for owin getting the hubcontext // Got this from here: https://stackoverflow.com/questions/29783898/owin-signalr-autofac var builder = new ContainerBuilder(); var connManager = hubConfig.Resolver.Resolve<IConnectionManager>(); builder.RegisterInstance(connManager) .As<IConnectionManager>() .SingleInstance(); builder.Update(container); container.Resolve<IBusControl>().Start(); }
protected void ConfigIoc() { var builder = new ContainerBuilder(); builder.RegisterType<MainWindowViewModel>(); builder.RegisterType<MainWindow>().As<IViewFor<MainWindowViewModel>>(); builder.RegisterInstance(this).As<IScreen>(); var container = builder.Build(); RxApp.ConfigureServiceLocator( (iface, contract) => { if (contract != null) return container.ResolveNamed(contract, iface); return container.Resolve(iface); }, (iface, contract) => { Type constructed = typeof(IEnumerable<>).MakeGenericType(new[] { iface }); if (contract != null) return container.ResolveNamed(contract, constructed) as IEnumerable<object>; return container.Resolve(constructed) as IEnumerable<object>; }, (realClass, iface, contract) => { var b = new ContainerBuilder(); if (contract != null) b.RegisterType(realClass).Named(contract, iface); else b.RegisterType(realClass).As(iface); b.Update(container); }); }
protected void Application_Start() { MvcHandler.DisableMvcResponseHeader = true; log4net.Config.XmlConfigurator.Configure(); BootStrapper.BootStrap(); var container = BootStrapper.Container; var builder = new ContainerBuilder(); var config = GlobalConfiguration.Configuration; builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterWebApiFilterProvider(config); builder.Update(container); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); AreaRegistration.RegisterAllAreas(); // fluent validation DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; GlobalConfiguration.Configuration.Services.Add(typeof(System.Web.Http.Validation.ModelValidatorProvider), new FluentValidationModelValidatorProvider(new ValidatorFactory())); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); }
public void Update(ContainerBuilder cb) { if (_rootScope == null) throw new ZenCoreException("Ядро Zen.Core не получило контейнер при построении. Функционал не доступен."); cb.Update(_rootScope.ComponentRegistry); }
public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> RegisterOwinApplicationContainer(this ContainerBuilder builder) { return builder.Register(ctx => { ILifetimeScope scope = ctx.Resolve<ILifetimeScope>().BeginLifetimeScope(); IComponentRegistry registry = scope.ComponentRegistry; ContainerBuilder newBuilder = new ContainerBuilder(); newBuilder.Register(c => new RuntimeRegistrationDelegate(func => { Tuple<Type, object> registerResult = func(scope as IServiceProvider); ContainerBuilder innerNewBuilder = new ContainerBuilder(); innerNewBuilder.Register(_ => registerResult.Item2) .As(registerResult.Item1) .ExternallyOwned(); innerNewBuilder.Update(registry); })).As<RuntimeRegistrationDelegate>().InstancePerLifetimeScope(); newBuilder.Update(registry); return scope as IServiceProvider; }).As<IServiceProvider>() as IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>; }
public void AnotherMockWorks() { var builder = new ContainerBuilder(); var vp = new Mock<IVersionProvider>(); vp.Setup(v => v.GetVersion()).Returns(new Version("1.0.0.0")); builder.RegisterInstance(vp.Object).As<IVersionProvider>(); var container = builder.Build(); var versionProvider1 = container.Resolve<IVersionProvider>(); var builder2 = new ContainerBuilder(); var vp2 = new Mock<IVersionProvider>(); vp2.Setup(v => v.GetVersion()).Returns(new Version("2.0.0.0")); builder2.RegisterInstance(vp2.Object).As<IVersionProvider>(); builder2.Update(container); var versionProvider2 = container.Resolve<IVersionProvider>(); Assert.That(versionProvider2.GetVersion(), Is.EqualTo(new Version("2.0.0.0"))); Assert.That(versionProvider1.GetVersion(), Is.EqualTo(new Version("1.0.0.0"))); }
protected void Application_Start() { var container = Container.Instance; var builder = new ContainerBuilder(); Container.Configure_Raven(builder); builder.RegisterControllers(typeof(MvcApplication).Assembly); // http://code.google.com/p/autofac/wiki/Mvc3Integration //builder.RegisterModelBinders(Assembly.GetExecutingAssembly()); //builder.RegisterModelBinderProvider(); builder.RegisterType<References>(); builder.RegisterType<Scenario>(); builder.Update(container); AutofacHostFactory.Container = container; DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); BundleTable.Bundles.RegisterTemplateBundles(); }
// The bootstrapper enables you to reconfigure the composition of the framework, // by overriding the various methods and properties. // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper //protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines) //{ // // No registrations should be performed in here, however you may // // resolve things that are needed during application startup. //} //protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer) //{ // // Perform registration that should have an application lifetime //} protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context) { // Perform registrations that should have a request lifetime var builder = new ContainerBuilder(); builder.RegisterModule(new ServicesModule()); builder.Update(container.ComponentRegistry); }
/// <summary> /// 设置MVC的DependencyResolver注册点 /// </summary> /// <param name="assemblies"></param> protected void SetResolver(Assembly[] assemblies) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(assemblies).AsSelf(); builder.Update(Container); DependencyResolver.SetResolver(new AutofacDependencyResolver(Container)); }
private void AutofacInit() { Type flagMeta = typeof(Model.IAutofacFlag); //bin下的所有程序集 List <System.Reflection.Assembly> lst = new List <System.Reflection.Assembly>(); // var System.Reflection.Assembly.LoadFrom("Azeroth.WCH.Bll.dll"); System.Reflection.Assembly[] allAssembly = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast <System.Reflection.Assembly>().ToArray(); //AppDomain.CurrentDomain.GetAssemblies().ToArray(); //标识接口派生的类和接口 var allMeta = allAssembly.SelectMany(x => x.GetTypes()).Where(x => flagMeta.IsAssignableFrom(x) && x != flagMeta).ToArray(); var builder = new Autofac.ContainerBuilder(); builder.RegisterTypes(allMeta) .AsSelf() .AsImplementedInterfaces() .InstancePerLifetimeScope() .PropertiesAutowired(); //PropertiesAutowired注册为属性注入类型,所有实现IAutofacFlag的注册为InstancePerLifetimeScope生命周期 builder.Update(Container); builder = new ContainerBuilder(); builder.RegisterControllers(allAssembly) .AsSelf() .InstancePerLifetimeScope() .PropertiesAutowired(); builder.Update(Container); DependencyResolver.SetResolver(new AutofacDependencyResolver(Container)); }
public void RegisterDependencies(Action<ContainerBuilder> build) { var cb = new ContainerBuilder(); build?.Invoke(cb); cb.Update(DependencyContainer); }
/// <summary> /// 注册自定义类型 /// </summary> protected override void RegisterCustomTypes() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterInstance(this).As<IIocInitializer>().SingleInstance(); builder.RegisterType<MvcIocResolver>().As<IIocResolver>().SingleInstance(); builder.Update(Container); }
public void RegisterWithPhoneService(Type service, string phoneStateKey, Type implementation) { var pservice = (IPhoneService)GetInstance(typeof(IPhoneService), null); if (!pservice.State.ContainsKey(phoneStateKey ?? service.FullName)) { pservice.State[phoneStateKey ?? service.FullName] = context.Resolve(implementation); } var builder = new ContainerBuilder(); builder.Register(c => { var phoneService = c.Resolve<IPhoneService>(); if (phoneService.State.ContainsKey(phoneStateKey ?? service.FullName)) { return phoneService.State[phoneStateKey ?? service.FullName]; } return c.Resolve(implementation); }).Named(phoneStateKey, service) .OnActivated(args => OnActivated(args.Instance)); builder.Update(context.ComponentRegistry); }
protected void Application_Start() { #region ApplicationStart ContainerBuilder builder = new ContainerBuilder(); // Register MVC controllers. builder.RegisterControllers(typeof(MvcApplication).Assembly); // Set the dependency resolver to be Autofac. IContainer container = builder.Build(); EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.MvcInjection.WebApplication"); // instruct NServiceBus to use a custom AutoFac configuration endpointConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container)); endpointConfiguration.UseSerialization<JsonSerializer>(); endpointConfiguration.UsePersistence<InMemoryPersistence>(); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); endpoint = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult(); ContainerBuilder updater = new ContainerBuilder(); updater.RegisterInstance(endpoint); updater.Update(container); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); #endregion }
protected override void ConfigureApplicationContainer(ILifetimeScope container) { base.ConfigureApplicationContainer(container); var builder = new ContainerBuilder(); builder.RegisterType<AppSettings>().As<IAppSettings>().SingleInstance(); builder.RegisterType<DummyMailChimpWebhooks>().As<IMailChimpWebhooks>().SingleInstance(); builder.RegisterType<DummyMailgunWebhooks>().As<IMailgunWebhooks>().SingleInstance(); builder.RegisterType<AzureTableStorageTodoService>().As<ITodoService>().SingleInstance(); // Consumers and sagas builder.RegisterAssemblyTypes(typeof(Bootstrapper).Assembly) .Where(t => t.Implements<ISaga>() || t.Implements<IConsumer>()) .AsSelf(); // Saga repositories builder.RegisterGeneric(typeof(InMemorySagaRepository<>)) .As(typeof(ISagaRepository<>)) .SingleInstance(); // Service bus builder.Register(c => ServiceBusFactory.New(sbc => { sbc.ReceiveFrom("loopback://localhost/queue"); sbc.Subscribe(x => x.LoadFrom(container)); })).As<IServiceBus>().SingleInstance(); builder.Update(container.ComponentRegistry); }
public static IContainer Update(this IContainer container, Action<ContainerBuilder> updateAction) { var updater = new ContainerBuilder(); updateAction(updater); updater.Update(container); return container; }
/// <summary> /// 注册自定义类型 /// </summary> protected override void RegisterCustomTypes() { base.RegisterCustomTypes(); ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<Program>().PropertiesAutowired().SingleInstance(); builder.Update(Container); }
protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer) { var setup = new Setup((IContainer)existingContainer); // defaults setup.WithGuidGenerator(); setup.WithThreadStaticTenantContext(); setup.WithMongo("MongoConnectionReadModel"); setup.RegisterReadModelRepositories(); // web specific var builder = new ContainerBuilder(); builder.RegisterType<NancyUserMapper>().As<IUserMapper>(); builder.RegisterType<StaticContentResolverForInMemory>().As<IStaticContentResolver>(); builder.RegisterType<ExcelService>().As<IExcelService>(); builder.Update(setup.Container.ComponentRegistry); // bus setup.WithInMemoryBus(); setup.RegisterReadModelHandlers(); // eventstore setup.WithMongoEventStore("MongoConnectionEventStore", new AuthorizationPipelineHook(setup.Container), new MessageDispatcher(setup.Container), false); // start the bus setup.Container.Resolve<IServiceBus>().Start(ConfigurationManager.AppSettings["serviceBusEndpoint"]); }
protected override void ConfigureRequestContainer(Autofac.ILifetimeScope existingContainer) { var builder = new ContainerBuilder(); builder.RegisterType<IdeastrikeContext>() .AsSelf() .SingleInstance(); builder.RegisterType<IdeaRepository>() .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<ActivityRepository>() .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<FeatureRepository>() .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<SettingsRepository>() .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<UserRepository>() .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<ImageRepository>() .AsImplementedInterfaces() .SingleInstance(); builder.Update(existingContainer.ComponentRegistry); }
private static void Main(string[] args) { var builder = new ContainerBuilder(); builder.Register(x => x.Resolve<ISessionFactoryBuilder>().Build()).SingleInstance().As<ISessionFactory>(); builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()); builder.Register(x => x.Resolve<ISessionFactory>().OpenStatelessSession()); builder.RegisterType<UnitOfWork>().As<IUnitOfWork>(); builder.RegisterType<BenchSuite>().AsSelf(); builder.RegisterType<SessionHelper>().As<ISessionHelper>(); builder.RegisterType<SqliteSessionFactoryBuilder>().As<ISessionFactoryBuilder>().SingleInstance(); var container = builder.Build(); var suite = container.Resolve<BenchSuite>(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Sqlite"); Console.ResetColor(); suite.Run(); builder = new ContainerBuilder(); builder.RegisterType<MsSqlSessionFactoryBuilder>().As<ISessionFactoryBuilder>().SingleInstance(); builder.Register(x => x.Resolve<ISessionFactoryBuilder>().Build()).SingleInstance().As<ISessionFactory>(); builder.Update(container); suite = container.Resolve<BenchSuite>(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Mssql"); Console.ResetColor(); suite.Run(); Console.ReadKey(); }
public void RegisterHandlers(Assembly assembly) { _logger.Info("Registering handlers from " + assembly.FullName); var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(assembly) .Where(t => t.Name.EndsWith("Handlers")) //TODO should become => implements ihandleevent .AsSelf(); builder.Update(_container.ComponentRegistry); foreach (var type in assembly.GetTypes()) { foreach (var handlerInterfaceType in type.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandleEvent<>))) { var messageType = handlerInterfaceType.GetGenericArguments().First(); if (!_eventTypesWithHandlers.ContainsKey(messageType)) { _eventTypesWithHandlers.Add(messageType, new List<Type>()); } _eventTypesWithHandlers[messageType].Add(type); } } _logger.Info("The service bus contains {0} handlers for {1} event types", _eventTypesWithHandlers.Values.Sum(h => h.Count), _eventTypesWithHandlers.Count); }
// Perform registration that should have an application lifetime protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer) { _logger.Debug("ConfigureApplicationContainer"); base.ConfigureApplicationContainer(existingContainer); //When using assembly scanning with IIS applications, you can run into a little trouble depending on how you do the assembly location. (This is one of our FAQs) //When hosting applications in IIS all assemblies are loaded into the AppDomain when the application first starts, but when the AppDomain is recycled by IIS the assemblies are then only loaded on demand. //To avoid this issue use the GetReferencedAssemblies() method on System.Web.Compilation.BuildManager to get a list of the referenced assemblies instead: //var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>(); var asms = AppDomain.CurrentDomain.GetAssemblies(); //.Where(asm =>asm.GetCustomAttributes().Any(attr => attr.GetType() == typeof(IncludeInNancyAssemblyScanningAttribute))); var builder = new ContainerBuilder(); //foreach (var asm in asms) //{ // builder.RegisterAssemblyTypes(asm).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces(); //} builder.RegisterModule<Nancy.Demo.Data.DataModule>(); builder.RegisterModule<NancyDemo.Services.ServiceModule>(); builder.RegisterType<Tokenizer>().As<ITokenizer>(); builder.Update(existingContainer.ComponentRegistry); }
private void AddSignalRInjection(IContainer container,IDependencyResolver resolver) { var updater = new ContainerBuilder(); updater.RegisterInstance(resolver.Resolve<IConnectionManager>()); updater.Update(container); }
protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer) { var builder = new ContainerBuilder(); _tasks.ForEach(task => task.Task.Invoke(builder)); builder.Update(existingContainer.ComponentRegistry); base.ConfigureApplicationContainer(existingContainer); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); ContainerBuilder builder0 = new ContainerBuilder(); var Container = builder0.Build(); Type baseType = typeof(Model.IDependency); System.Reflection.Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies().ToArray(); //获取已加载到此应用程序域的执行上下文中的程序集。 Type[] dependencyTypes = assemblies .SelectMany(s => s.GetTypes()) .Where(p => baseType.IsAssignableFrom(p) && p != baseType).ToArray(); //得到接口和实现类 //RegisterDependencyTypes(dependencyTypes); //第一步:注册类型 Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder(); //builder.RegisterType<DbContextScopeFactory>() // .As<IDbContextScopeFactory>() // .AsSelf() // .AsImplementedInterfaces() // .InstancePerLifetimeScope() // .PropertiesAutowired(); builder.RegisterTypes(dependencyTypes) .AsSelf() .AsImplementedInterfaces() .InstancePerLifetimeScope() .PropertiesAutowired(); //PropertiesAutowired注册为属性注入类型,所有实现IDependency的注册为InstancePerLifetimeScope生命周期 builder.Update(Container); //SetResolver(assemblies); //第二步: ContainerBuilder builder2 = new ContainerBuilder(); builder2.RegisterControllers(assemblies) .AsSelf() .InstancePerLifetimeScope() .PropertiesAutowired(); builder2.Update(Container); DependencyResolver.SetResolver(new AutofacDependencyResolver(Container)); }
private void FinishInit(string userNameForHistoryAndNotes, ContainerBuilder builder) { _user = new ChorusUser(userNameForHistoryAndNotes); builder.RegisterInstance(_user).As <IChorusUser>(); // builder.RegisterGeneratedFactory<NotesInProjectView.Factory>().ContainerScoped(); // builder.RegisterGeneratedFactory<NotesInProjectViewModel.Factory>().ContainerScoped(); // builder.RegisterGeneratedFactory<NotesBrowserPage.Factory>().ContainerScoped(); // builder.Register(new NullProgress());//TODO _container = builder.Build(); //add the container itself var builder2 = new Autofac.ContainerBuilder(); builder2.RegisterInstance(_container).As <IContainer>(); builder2.Update(_container); DidLoadUpCorrectly = true; }
/// <summary> /// 依赖注册 /// </summary> /// <param name="config">配置对象</param> protected virtual void RegisterDependencies(SmartConfig config) { // 初始化容器 var builder = new Autofac.ContainerBuilder(); this._container = builder.Build(); #region 注册依赖实例 builder = new Autofac.ContainerBuilder(); builder.RegisterInstance(config.TypeFinder).As <ITypeFinder>().SingleInstance(); builder.RegisterInstance(config).As <SmartConfig>().SingleInstance(); builder.RegisterInstance(this).As <IContainerManager>().SingleInstance(); builder.RegisterType <Caching.HttpCache>().Named <Caching.ICache>("smart.lang").SingleInstance(); builder.Update(this._container); #endregion #region 注册实现 IDependency 接口的依赖类型 builder = new Autofac.ContainerBuilder(); var dependencies = config.TypeFinder.ForTypesDerivedFrom <IDependency>().ToList(); foreach (var dependency in dependencies) { var reg = builder.RegisterType(dependency) .AsImplementedInterfaces() // 注册所有接口 .PropertiesAutowired(); // 自动属性注入 if (typeof(ISingletonDependency).IsAssignableFrom(dependency)) { reg.SingleInstance(); } else if (typeof(ITransientDependency).IsAssignableFrom(dependency)) { reg.InstancePerDependency(); } else { reg.InstancePerLifetimeScope(); } } builder.Update(this._container); #endregion #region 注册其他程序集所提供的依赖关系(实现 IDependencyRegistrar 接口的类) builder = new ContainerBuilder(); var drInstances = config.TypeFinder.ForTypesDerivedFrom <IDependencyRegistrar>() .ToInstances <IDependencyRegistrar>() .OrderBy(t => t.Order) .ToList(); foreach (var dependencyRegistrar in drInstances) { dependencyRegistrar.Register(builder, config); } builder.Update(this._container); #endregion // 注册完成后处理 if (config.OnDependencyRegistered != null) { config.OnDependencyRegistered(this._container); } }