Ejemplo n.º 1
0
        public static IContainer BuildContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<StatisticsViewModel>();
            builder.RegisterType<DetailsViewModel>();

            builder.RegisterType<MainView>();
            builder.RegisterType<MainViewModel>();
            builder.RegisterType<CameraView>();
            builder.RegisterType<CameraViewModel>();

            builder.RegisterType<MvxMessengerHub>().As<IMvxMessenger>().SingleInstance();
            builder.RegisterType<ApplicationDataRepository>().As<IApplicationDataRepository>();

            builder.RegisterAssemblyTypes(typeof(MyShuttleClient).Assembly)
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(typeof(MyShuttleClient).Assembly)
                .Where(t => t.Name.EndsWith("ServiceSingleton"))
                .AsImplementedInterfaces().SingleInstance();

            builder.RegisterType<MyShuttleClient>().As<IMyShuttleClient>();

            return builder.Build();
        }
Ejemplo n.º 2
0
        public static void Launch()
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterType <Tasks.TaskException>();
            builder.RegisterType <Tasks.TaskSyncLineShiftPerfLastShift>();
            builder.RegisterType <Tasks.TaskOEEActionManagement>();
            builder.RegisterType <UnitOfWork>()
            .As <IUnitOfWork>()
            .InstancePerBackgroundJob();

            builder.RegisterType <DatabaseFactory>()
            .As <IDatabaseFactory>()
            .InstancePerBackgroundJob();

            builder.RegisterAssemblyTypes(typeof(SystemFunctionRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces()
            .InstancePerBackgroundJob();

            builder.RegisterAssemblyTypes(typeof(SystemService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerBackgroundJob();

            Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(builder.Build());
        }
Ejemplo n.º 3
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

              var nancyAssembly = typeof(AppModule).Assembly;

              // Register validators
              builder.RegisterAssemblyTypes(nancyAssembly)
             .AsClosedTypesOf(typeof(IValidator<>))
             .SingleInstance();

              // register all query handlers
              builder.RegisterAssemblyTypes(nancyAssembly)
             .Where(t => t.IsClosedTypeOf(typeof(IHandler<>)))
             .AsImplementedInterfaces();
              builder.RegisterAssemblyTypes(nancyAssembly)
             .Where(t => t.IsClosedTypeOf(typeof(IHandler<,>)))
             .As(t => new KeyedService("queryHandler", t.GetInterfaces().Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandler<,>))));
              builder.RegisterGenericDecorator(typeof(RequestValidationAwareHandler<,>), typeof(IHandler<,>), "queryHandler");

              // Register other stuff
              builder.RegisterType<NancyIdentityFromContextAssigner>()
             .AsImplementedInterfaces()
             .SingleInstance();
              builder.RegisterType<NancySecurityContextFactory>()
             .AsImplementedInterfaces()
             .SingleInstance();
        }
Ejemplo n.º 4
0
        protected override void Load(ContainerBuilder builder)
        {
            //Register injectables
            LoadInjectables(builder);
            LoadSettings(builder);

            //Regiser auto mapper profiles
            builder.RegisterAssemblyTypes(typeof (BaseService).Assembly)
                .Where(t => typeof (Profile).IsAssignableFrom(t) && !t.IsAbstract)
                .As<Profile>()
                .SingleInstance();

            //Register validation system
            builder.RegisterType<AutofacFactory>().AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterType<JsonNetConverter>().AsImplementedInterfaces().InstancePerRequest();
            var validatorTypes = typeof (BaseService).Assembly.GetTypes()
                .Union(typeof(Entity).Assembly.GetTypes())
                .Where(t => typeof (IValidator).IsAssignableFrom(t) || typeof(IObjectValidator).IsAssignableFrom(t))
                .Where(t => !t.IsGenericType)
                .ToList();
            var staticValidators =
                validatorTypes.Where(t => t.IsDefined(typeof (StaticValidatorAttribute), false)).ToList();
            var otherValidators = validatorTypes.Except(staticValidators).ToList();

            staticValidators.ForEach(t => builder.RegisterType(t).AsImplementedInterfaces().AsSelf().SingleInstance());
            otherValidators.ForEach(t => builder.RegisterType(t).AsImplementedInterfaces().AsSelf().InstancePerRequest());

            //Register identity
            builder.RegisterType<VaBankIdentity>()
                .AsSelf()
                .InstancePerRequest();

            //Register operation provider
            builder.RegisterType<ServiceOperationProvider>()
                .AsSelf()
                .InstancePerRequest();

            //Register dependency collections
            builder.RegisterAssemblyTypes(typeof (BaseService).Assembly)
                .Where(t => typeof (IDependencyCollection).IsAssignableFrom(t))
                .PropertiesAutowired()
                .AsSelf()
                .InstancePerRequest();

            //Register service bus
            builder.RegisterInstance(VaBankServiceBus.Instance)
                .AsImplementedInterfaces()
                .SingleInstance();

            //Register services
            builder.RegisterAssemblyTypes(typeof (BaseService).Assembly)
                .Where(t => typeof (IService).IsAssignableFrom(t))
                .AsImplementedInterfaces()
                .InstancePerRequest();

            //Register startup class
            builder.RegisterType<ApplicationStartup>()
                .AsImplementedInterfaces()
                .SingleInstance();
        }
Ejemplo n.º 5
0
        private bool Compose()
        {
             var builder = new ContainerBuilder();
             try
             {
                 builder.RegisterAssemblyTypes((typeof(DomainModule).Assembly));
                 builder.RegisterAssemblyTypes((typeof(NetworkModule).Assembly));
                 builder.RegisterAssemblyTypes((typeof(ApplicationModule).Assembly));

                 builder.RegisterModule<DomainModule>();
                 builder.RegisterModule<NetworkModule>();
                 builder.RegisterModule<ApplicationModule>();

                 builder.RegisterType<MessageService>().As<IMessageService>();
                 builder.RegisterType<InterfaceSelectionView>().As<IInterfaceSelectionView>();
                 builder.RegisterType<SharesView>().As<ISharesView>();
                 builder.RegisterType<Query>().As<IQuery>();

                 container = builder.Build();
                 builder = new ContainerBuilder();
                 builder.RegisterInstance<IContainer>(container).SingleInstance();
                 builder.Update(container);
                 return true;
             }
             catch
             {
                 return false;
             }
        }
Ejemplo n.º 6
0
        private static void RegisterServices(ContainerBuilder builder)
        {
            builder.Register(x => new AppDbContext())
                .As<DbContext>()
                .InstancePerRequest();
            builder.Register(x => new HttpCacheService())
                .As<ICacheService>()
                .InstancePerRequest();
            builder.Register(x => new IdentifierProvider())
                .As<IIdentifierProvider>()
                .InstancePerRequest();
            builder.Register(x => new DropdownListService())
                .As<IDropdownListService>()
                .InstancePerRequest();

            var servicesAssembly = Assembly.GetAssembly(typeof(IPostsService));
            builder.RegisterAssemblyTypes(servicesAssembly).AsImplementedInterfaces();

            builder.RegisterGeneric(typeof(DbRepository<>))
                .As(typeof(IDbRepository<>))
                .InstancePerRequest();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AssignableTo<BaseController>().PropertiesAutowired();
        }
        private static void SetIocContainer()
        {
            //Implement Autofac

            var configuration = GlobalConfiguration.Configuration;
            var builder = new ContainerBuilder();

            // Register MVC controllers using assembly scanning.
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            // Register MVC controller and API controller dependencies per request.
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerLifetimeScope();

            // Register service
            builder.RegisterAssemblyTypes(typeof(ProfileService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces().InstancePerDependency();

            // Register repository
            builder.RegisterAssemblyTypes(typeof(ProfileRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerDependency();

            var container = builder.Build();

            //for MVC Controller Set the dependency resolver implementation.
            var resolverMvc = new AutofacDependencyResolver(container);
            System.Web.Mvc.DependencyResolver.SetResolver(resolverMvc);
        }
Ejemplo n.º 8
0
        static void RegisterUI(ContainerBuilder builder)
        {
            //  register view models
            builder.RegisterAssemblyTypes(PapercutContainer.ExtensionAssemblies)
                .Where(type => type.Name.EndsWith("ViewModel"))
                .AsImplementedInterfaces()
                .AsSelf()
                .OnActivated(SubscribeEventAggregator)
                .InstancePerDependency();

            //  register views
            builder.RegisterAssemblyTypes(PapercutContainer.ExtensionAssemblies)
                .Where(type => type.Name.EndsWith("View"))
                .AsImplementedInterfaces()
                .AsSelf()
                .OnActivated(SubscribeEventAggregator)
                .InstancePerDependency();

            // register ui scope services
            builder.RegisterAssemblyTypes(PapercutContainer.ExtensionAssemblies)
                .Where(type => type.Namespace != null && type.Namespace.EndsWith("Services"))
                .AsImplementedInterfaces()
                .AsSelf()
                .InstancePerUIScope();
        }
Ejemplo n.º 9
0
        protected override void Load(ContainerBuilder builder)
        {
            //Modules
            builder.RegisterModule<CoreModule>();
            builder.RegisterModule<DataAccessModule>();
            builder.RegisterModule<ServicesModule>();

            //Automapper profiles
            builder.RegisterAssemblyTypes(typeof(BaseJob<>).Assembly)
                .Where(t => typeof(Profile).IsAssignableFrom(t) && !t.IsAbstract)
                .As<Profile>()
                .SingleInstance();

            builder.RegisterInstance(_serviceBus)
                .AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(ThisAssembly)
                .Where(typeof (IJobContext).IsAssignableFrom)
                .AsSelf()
                .PropertiesAutowired()
                .InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(DefaultJobContext<>))
                .As(typeof(IJobContext<>))
                .AsSelf()
                .InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(ThisAssembly)
                .Where(typeof (IJob).IsAssignableFrom)
                .Where(x => !x.IsAbstract)
                .AsSelf()
                .AsImplementedInterfaces()
                .SingleInstance();
            builder.RegisterType<JobSettingsProvider>().AsSelf().InstancePerDependency();
            builder.RegisterType<JobStartup>().AsSelf().SingleInstance();
        }
Ejemplo n.º 10
0
        private static void SetAutofacContainer(string dbConnectionString)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<DefaultValidationBus>().As<IValidationBus>().InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(Assembly.Load("Utilities")).AsImplementedInterfaces().InstancePerHttpRequest();

            builder.RegisterType<ScrabbleClubContext>().WithParameter("connectionStringName", dbConnectionString).InstancePerHttpRequest();

            var infrastructureDataAccessLayerAssembly = Assembly.Load("DataAccess");
            builder.RegisterAssemblyTypes(infrastructureDataAccessLayerAssembly)
                   .Where(t => t.Name.EndsWith("Repository"))
                   .AsImplementedInterfaces().InstancePerHttpRequest();

            var domainLayerAssembly = Assembly.Load("Domain");
            builder.RegisterAssemblyTypes(domainLayerAssembly)
                   .Where(t => t.Name.EndsWith("Service"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();

            var applicationLayerAssembly = Assembly.Load("Application");
            builder.RegisterAssemblyTypes(applicationLayerAssembly)
                   .AsClosedTypesOf(typeof (IValidationHandler<>)).InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(applicationLayerAssembly)
                   .Where(t => t.Name.EndsWith("Service"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();

            builder.RegisterFilterProvider();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 11
0
        protected override void Load(ContainerBuilder b)
        {
            // TODO: Replace with SiderDomainRoot
              b.RegisterType<VolatileDomainRoot>()
            .As<IDomainRoot>()
            .InstancePerDependency();

              b.RegisterAssemblyTypes(typeof(IRepository).Assembly)
            .AssignableTo<IRepository>()
            .AsSelf()
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .InstancePerDependency();

              b.RegisterAssemblyTypes(typeof(IFactory).Assembly)
            .AssignableTo<IFactory>()
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .SingleInstance();

              b.RegisterAssemblyTypes(typeof(IDataService).Assembly)
            .AssignableTo<IDataService>()
            .AsSelf()
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .SingleInstance();
        }
Ejemplo n.º 12
0
        public static void Bootstrap()
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyTypes(typeof (IHandle<>).Assembly)
                .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(typeof(Denormalizer<>).Assembly)
                .AsImplementedInterfaces();

            //HACK
            builder.RegisterInstance(new Replay.Runner().Rebuild())
                .AsImplementedInterfaces()
                .SingleInstance();

            builder.RegisterModule<EventStoreModule>();
            builder.RegisterType<SignalREventDispatcher>()
                .AsImplementedInterfaces()
                .SingleInstance();

            builder.RegisterType<InProcessCommandProcessor>()
                .AsImplementedInterfaces()
                .SingleInstance();

            builder.RegisterSource(new ContravariantRegistrationSource());

            var container = builder.Build();

            Command.UseContainer(container.BeginLifetimeScope());
            Denormalizer.UseContainer(container.BeginLifetimeScope());
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
        public static void Register(IAppBuilder app, HttpConfiguration config)
        {
            var aspNetIdentityAssembly = typeof(IMarkerAspNetIdentityInterface).Assembly;
            var cornhouseCoreAssembly = typeof (IMarkerCornhouseCoreInterface).Assembly;
            var executingAssembly = Assembly.GetExecutingAssembly();
            
            var builder = new ContainerBuilder();

            builder.Register(c => InitializeRavenDb.Initialize(aspNetIdentityAssembly)).As<IDocumentStore>().InstancePerLifetimeScope();
            builder.Register(c => c.Resolve<IDocumentStore>().OpenAsyncSession()).As<IAsyncDocumentSession>().InstancePerRequest();
            builder.Register(c => HttpContext.Current.User).InstancePerRequest();

            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationRoleManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<RavenUserStore>().AsSelf().InstancePerRequest();
            builder.RegisterType<RavenRoleStore>().AsSelf().InstancePerRequest();
            

            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();

            builder.RegisterApiControllers(executingAssembly);
            builder.RegisterApiControllers(aspNetIdentityAssembly);

            builder.RegisterAssemblyTypes(executingAssembly).AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterAssemblyTypes(aspNetIdentityAssembly).AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterAssemblyTypes(cornhouseCoreAssembly).AsImplementedInterfaces().InstancePerRequest();
            
            
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);            
        }
Ejemplo n.º 14
0
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();
            //builder.RegisterModule<ConfigurationSettingsReader>();
            builder.RegisterModule<MvcModule>();
            builder.RegisterModule<Log4NetModule>();
            builder.RegisterModule<NHibernateModule>();

            builder.RegisterAssemblyTypes(typeof (MvcApplication).Assembly)
                .AsClosedTypesOf(typeof (DomainEventBase<>))
                .AsImplementedInterfaces()
                .InstancePerHttpRequest();

            builder.RegisterAssemblyTypes(typeof (MvcApplication).Assembly)
                .AsClosedTypesOf(typeof(IHandleEvent<>))
                .AsImplementedInterfaces()
                .InstancePerHttpRequest();

            builder.RegisterType<EventDispatchHandler>().AsSelf().InstancePerHttpRequest();

            builder.RegisterType<DomainEventsManager>().As<IDomainEventsManager>().SingleInstance();
            builder.Register(c => c.Resolve<IDomainEventsManager>().SpawnLocal())
                .As<ILocalEventsManager>()
                .As<IPublishDomainEvent>()
                .InstancePerHttpRequest();

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
Ejemplo n.º 15
0
        static IContainer BuildContainer()
        {
            var builder = new ContainerBuilder();
            var thisAssembly = typeof (Program).GetTypeInfo().Assembly;

            builder.RegisterModule(new LoggingModule());

            builder.RegisterAssemblyTypes(thisAssembly).As<ICommand>().AsSelf();
            builder.RegisterType<CommandLocator>().As<ICommandLocator>();

            builder.RegisterAssemblyTypes(thisAssembly).As<IExporter>().AsSelf();
            builder.RegisterAssemblyTypes(thisAssembly).As<IImporter>().AsSelf();
            builder.RegisterType<ExporterLocator>().As<IExporterLocator>();
            builder.RegisterType<ImporterLocator>().As<IImporterLocator>();

            builder.RegisterType<ReleasePlanBuilder>().As<IReleasePlanBuilder>().SingleInstance();
            builder.RegisterType<PackageVersionResolver>().As<IPackageVersionResolver>().SingleInstance();
            builder.RegisterType<ChannelVersionRuleTester>().As<IChannelVersionRuleTester>().SingleInstance();

            builder.RegisterType<OctopusClientFactory>().As<IOctopusClientFactory>();
            builder.RegisterType<OctopusRepositoryFactory>().As<IOctopusAsyncRepositoryFactory>();

            builder.RegisterType<OctopusPhysicalFileSystem>().As<IOctopusFileSystem>();

            return builder.Build();
        }
Ejemplo n.º 16
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(typeof (IUnit<>).Assembly)
                   .Where(t => t.IsUnit())
                   .AsClosedTypesOf(typeof (IUnit<>))
                   .As(t => new KeyedService(t.Name, typeof (IUnit<>).MakeGenericType(t)));

            builder.RegisterAssemblyTypes(typeof (IUnitFactory<>).Assembly)
                   .Where(t => t.IsUnitFactory())
                   .AsClosedTypesOf(typeof (IUnitFactory<>))
                   .SingleInstance();

            builder.RegisterAssemblyTypes(typeof (IProductionProject).Assembly)
                   .Where(t => t.IsProductionProject())
                   .AsSelf()
                   .SingleInstance();

            builder.Register(_ => new HashSet<IUnit>(new UnitEqualityComparer()))
                   .As<ISet<IUnit>>()
                   .SingleInstance();

            builder.RegisterType<SimpleFixedUnitLayer>()
                   .AsImplementedInterfaces()
                   .SingleInstance();
        }
Ejemplo n.º 17
0
        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();

            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerHttpRequest();

            builder.RegisterAssemblyTypes(typeof(CompanyRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerHttpRequest();

            builder.RegisterAssemblyTypes(typeof(CompanyService).Assembly)
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces().InstancePerHttpRequest();

            builder.RegisterAssemblyTypes(typeof(DefaultFormsAuthentication).Assembly)
             .Where(t => t.Name.EndsWith("Authentication"))
             .AsImplementedInterfaces().InstancePerHttpRequest();

            builder.Register(c => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ArchitectureEntities())))
                .As<UserManager<ApplicationUser>>().InstancePerHttpRequest();

            builder.RegisterFilterProvider();

            IContainer container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 18
0
        public ApplicationContainer()
        {
            var builder = new ContainerBuilder();
                //builder.RegisterModule<WhiteboxProfilingModule>();

                //default to InstancePerDependency, i.e., they it will make a new
                //one each time someone asks for one
                builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());

                builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                    .Where(t => t.GetInterfaces().Contains(typeof(ICommand))).InstancePerLifetimeScope();

                builder.Register(c => LocalizationManager).SingleInstance();

                if (Settings.Default.MruProjects==null)
                {
                    Settings.Default.MruProjects = new MostRecentPathsList();
                }
                builder.RegisterInstance(Settings.Default.MruProjects).SingleInstance();

                //this is to prevent some problems we were getting while waiting for a browser to navigate and being forced to call Application.DoEvents().
                //HtmlThumbnailer & ConfigurationDialog, at least, use this.
                builder.Register(c => new NavigationIsolator()).InstancePerLifetimeScope();

                builder.Register<HtmlThumbNailer>(c => new HtmlThumbNailer(c.Resolve<NavigationIsolator>())).SingleInstance();
                builder.Register<BookThumbNailer>(c => new BookThumbNailer(c.Resolve<HtmlThumbNailer>())).SingleInstance();

                _container = builder.Build();

                Application.ApplicationExit += OnApplicationExit;
        }
        public static ILifetimeScope CreateAutofacContainer(this IServiceCollection services, IConfigurationRoot configuration)
        {
            var builder = new ContainerBuilder();

            // Load web specific dependencies
            builder.RegisterType<AuthMessageSender>()
                .As<IEmailSender>().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(typeof(Startup).GetTypeInfo().Assembly).AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof (CartCommandService).GetTypeInfo().Assembly, typeof (ICartCommandService).GetTypeInfo().Assembly)
                .AsImplementedInterfaces();

            var databaseInitializer = new MigrateToLatestVersion(new SampleDataSeeder());
            builder.AddDataOnion(new DbContextConfig(configuration.GetConnectionString("DefaultConnection"), typeof(MusicStoreContext), databaseInitializer));

            // Populate the container with services that were previously registered
            builder.Populate(services);

            builder.RegisterType<BaseRepository<Album, MusicStoreContext>>().As<IRepository<Album>>();
            builder.RegisterType<BaseRepository<Artist, MusicStoreContext>>().As<IRepository<Artist>>();
            builder.RegisterType<BaseRepository<Cart, MusicStoreContext>>().As<IRepository<Cart>>();
            builder.RegisterType<BaseRepository<CartItem, MusicStoreContext>>().As<IRepository<CartItem>>();
            builder.RegisterType<BaseRepository<Genre, MusicStoreContext>>().As<IRepository<Genre>>();
            builder.RegisterType<BaseRepository<Order, MusicStoreContext>>().As<IRepository<Order>>();
            builder.RegisterType<BaseRepository<OrderDetail, MusicStoreContext>>().As<IRepository<OrderDetail>>();

            var container = builder.Build();

            return container;
        }
Ejemplo n.º 20
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register<IDealRepository>(x => new DealRepository(x.ResolveNamed<ISessionFactory>("ProjectSessionFactory"))).SingleInstance();
            builder.Register<IProjectRepository>(x => new ProjectRepository(x.ResolveNamed<ISessionFactory>("ProjectSessionFactory"))).SingleInstance();

            builder.RegisterAssemblyTypes(this.ThisAssembly)
               .Where(t => t.GetInterface(typeof(IView).Name) != null && !t.IsAbstract && t.IsPublic)
               .AsImplementedInterfaces()
               .SingleInstance()
               .OnActivated(x =>
               {
                   x.Context.Resolve<IEventBroker>().Subscribe(x.Instance);
               });

            builder.RegisterAssemblyTypes(this.ThisAssembly)
                .Where(t => t.GetInterface(typeof(IController).Name) != null && !t.IsAbstract && t.IsPublic)
                .AsImplementedInterfaces()
                .SingleInstance()
                .OnActivated(x =>
                {
                    x.Context.Resolve<IEventBroker>().Subscribe(x.Instance);
                });

            builder.RegisterAssemblyTypes(typeof(ProjectService).Assembly)
                .Where(t => t.GetInterface(typeof(IService).Name) != null && !t.IsAbstract && t.IsPublic)
                .AsImplementedInterfaces()
                .SingleInstance()
                .OnActivated(x =>
                {
                    x.Context.Resolve<IEventBroker>().Subscribe(x.Instance);
                });

            base.Load(builder);
        }
Ejemplo n.º 21
0
        protected override void Load(ContainerBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            foreach (var assemblyContainingMappings in AssembliesWithMappings)
            {
                builder.RegisterAssemblyTypes(assemblyContainingMappings)
                       .AsClosedTypesOf(typeof(ITypeConverter<,>))
                       .AsSelf();

                builder.RegisterAssemblyTypes(assemblyContainingMappings)
                       .AsClosedTypesOf(typeof(ValueResolver<,>))
                       .AsSelf();

                builder.RegisterAssemblyTypes(assemblyContainingMappings)
                       .AsClosedTypesOf(typeof(IMappingAction<,>))
                       .AsSelf();

                builder.RegisterAssemblyTypes(assemblyContainingMappings).Where(
                    t => typeof(Profile).IsAssignableFrom(t))
                    .As<Profile>().SingleInstance();
            }
        }
Ejemplo n.º 22
0
        private static void RegisterServices(ContainerBuilder builder)
        {
            builder.Register(x => new AcademyGrandPrixDbContext())
                .As<DbContext>()
                .InstancePerRequest();

            builder.Register(x => new HttpCacheService())
                .As<ICacheService>()
                .InstancePerRequest();

            builder.Register(x => new IdentifierProvider())
                .As<IIdentifierProvider>()
                .InstancePerRequest();

            var servicesAssembly = Assembly.GetAssembly(typeof(ITracksService));
            builder.RegisterAssemblyTypes(servicesAssembly).AsImplementedInterfaces();

            builder.RegisterGeneric(typeof(DbRepository<>))
                .As(typeof(IDbRepository<>))
                .InstancePerRequest();

            var infrastructureAssembly = Assembly.GetAssembly(typeof(ITracksPopulator));
            builder.RegisterAssemblyTypes(infrastructureAssembly).AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AssignableTo<BaseController>().PropertiesAutowired();
        }
Ejemplo n.º 23
0
        private static void RegisterServices(ContainerBuilder builder)
        {
            builder.Register(x => new TrueSnowDbContext())
                .As<DbContext>()
                .InstancePerRequest();
            builder.Register(x => new HttpCacheService())
                .As<ICacheService>()
                .InstancePerRequest();
            builder.Register(x => new IdentifierProvider())
                .As<IIdentifierProvider>()
                .InstancePerRequest();
            builder.Register(x => new HtmlSanitizerAdapter())
                .As<ISanitizer>()
                .InstancePerRequest();

            builder.RegisterType<UserStore<User>>()
                .As<IUserStore<User>>();
            builder.RegisterType<UserManager<User>>();

            var servicesAssembly = Assembly.GetAssembly(typeof(FilesService));
            builder.RegisterAssemblyTypes(servicesAssembly).AsImplementedInterfaces();

            builder.RegisterGeneric(typeof(DbRepository<>))
                .As(typeof(IDbRepository<>))
                .InstancePerRequest();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AssignableTo<BaseController>().PropertiesAutowired();
        }
Ejemplo n.º 24
0
        public static void Initialize()
        {
            var builder = new ContainerBuilder();

            //Configure for MVC
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            //Register repository
            builder.RegisterAssemblyTypes(typeof(ArtistRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces();

            //Register services
            builder.RegisterAssemblyTypes(typeof(PlaylistService).Assembly)
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces();

            //Configure database
            builder.Register<IDbConnection>(c =>
            {
                var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString);

                return conn;

            }).InstancePerRequest();

            //Create the container
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 25
0
        public static void RegisterDependencies()
        {
            var builder = new ContainerBuilder();

            builder.RegisterAssemblyTypes(Assembly.Load("DAL"))
                    .Where(t => t.Name.EndsWith("Repository"))
                    .AsImplementedInterfaces()
                    .InstancePerRequest();

            builder.RegisterAssemblyTypes(Assembly.Load("BO"))
                    .AsImplementedInterfaces()
                    .InstancePerRequest();

            // Note that ASP.NET MVC requests controllers by their concrete types,
            // so registering them As<IController>() is incorrect.
            // Also, if you register controllers manually and choose to specify
            // lifetimes, you must register them as InstancePerDependency() or
            // InstancePerHttpRequest() - ASP.NET MVC will throw an exception if
            // you try to reuse a controller instance for multiple requests.
            builder.RegisterControllers(typeof(MvcApplication).Assembly)
                   .InstancePerRequest();

            builder.RegisterAssemblyModules(typeof(MvcApplication).Assembly);

            builder.RegisterModule<AutofacWebTypesModule>();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
        }
Ejemplo n.º 26
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();

            builder.RegisterType<Entities>().As<IDbContext>().InstancePerLifetimeScope();
            builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(typeof(IRepository<>).Assembly).AsClosedTypesOf(typeof(IRepository<>)).InstancePerRequest();

            builder.RegisterAssemblyTypes(ServiceAssembly).Where(type => typeof(ServiceBase).IsAssignableFrom(type) && !type.IsAbstract).AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterAssemblyTypes(MapperAssembly).Where(type => typeof(MapperBase).IsAssignableFrom(type) && !type.IsAbstract).AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<RoleStore<IdentityRole>>().As<IRoleStore<IdentityRole, string>>().InstancePerRequest();
            builder.RegisterType<ApplicationRoleManager>().AsSelf().InstancePerRequest();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();

            builder.RegisterModule(new LoggingModule());

            builder.RegisterControllers(assemblies);

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
Ejemplo n.º 27
0
        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            builder.RegisterType<DefaultCommandBus>().As<ICommandBus>().InstancePerHttpRequest();
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerHttpRequest();

            builder.RegisterAssemblyTypes(typeof (UserRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerHttpRequest();

            //builder.RegisterAssemblyTypes(typeof (CategoryRepository).Assembly)
            //    .Where(t => t.Name.EndsWith("Repository"))
            //    .AsImplementedInterfaces().InstancePerHttpRequest();

            Assembly services = Assembly.Load("YiHe.Domain");

            builder.RegisterAssemblyTypes(services)
                .AsClosedTypesOf(typeof (ICommandHandler<>)).InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(services)
                .AsClosedTypesOf(typeof (IValidationHandler<>)).InstancePerHttpRequest();

            builder.RegisterType<DefaultFormsAuthentication>().As<IFormsAuthentication>().InstancePerHttpRequest();

            builder.RegisterFilterProvider();

            IContainer container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
        public static void RegisterDependencies()
        {
            //Create the builder
            var builder = new ContainerBuilder();
            
            //Setup common patterns
            builder.RegisterAssemblyTypes()
                   .Where(t => t.Name.EndsWith("Repository"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();
            builder.RegisterAssemblyTypes()
                   .Where(t => t.Name.EndsWith("Service"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();
            

            //Register all controllers for the assembly
            builder.RegisterControllers(typeof(MvcApplication).Assembly).InstancePerHttpRequest();


            //Register modules
            builder.RegisterAssemblyModules(typeof(MvcApplication).Assembly);
            builder.RegisterAssemblyModules(typeof(BusinessRegistry).Assembly);
            

            //Inject HTTP Abstractions
            builder.RegisterModule<AutofacWebTypesModule>();
            

            //Set the MVC dependency resolver to use Autofac
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
        private static void RegisterServices(ContainerBuilder builder)
        {
            builder.Register(x => new EntertainmentSystemDbContext())
                .As<DbContext>()
                .InstancePerRequest();

            builder.Register(x => new HttpCacheService())
                .As<ICacheService>()
                .InstancePerRequest();

            builder.Register(x => new IdentifierProvider())
                .As<IIdentifierProvider>()
                .InstancePerRequest();

            var usersServicesAssembly = Assembly.GetAssembly(typeof(UsersAdminService));
            builder.RegisterAssemblyTypes(usersServicesAssembly).AsImplementedInterfaces();

            var mediaServicesAssembly = Assembly.GetAssembly(typeof(MediaCategoryService));
            builder.RegisterAssemblyTypes(mediaServicesAssembly).AsImplementedInterfaces();

            var forumServicesAssembly = Assembly.GetAssembly(typeof(ForumPostService));
            builder.RegisterAssemblyTypes(forumServicesAssembly).AsImplementedInterfaces();

            var dropboxCloudStorage = Assembly.GetAssembly(typeof(DropboxCloudStorage));
            builder.RegisterAssemblyTypes(dropboxCloudStorage).AsImplementedInterfaces();

            builder.RegisterGeneric(typeof(DbRepository<>))
                .As(typeof(IDbRepository<>))
                .InstancePerRequest();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AssignableTo<BaseController>().PropertiesAutowired();
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Registers all types and sets the resolver for the dependencies
        /// </summary>
        /// <param name="context"></param>
        public static void Register(HttpContextBase context)
        {
            //Set Autofac as dependency resolver
            var builder = new ContainerBuilder();
            builder.RegisterIntegrationServices();
            builder.RegisterAssemblyTypes(Assembly.Load("NearForums.DataAccess"))
                .Where(t => t.Name.EndsWith("DataAccess"))
                .AsImplementedInterfaces()
                .InstancePerDependency();
            builder.RegisterAssemblyTypes(Assembly.Load("NearForums.Services"))
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .PropertiesAutowired()
                .InstancePerDependency();
            builder.RegisterNearforumsFilterProvider();
            builder.RegisterControllers(typeof(BaseController).Assembly)
                .PropertiesAutowired();
            builder.RegisterType<DatabaseSettingsRepository>()
                .As<ISettingsRepository>()
                .InstancePerDependency();
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            //Inject configuration dependencies
            SiteConfiguration.SettingsRepository = container.Resolve<ISettingsRepository>();
            SiteConfiguration.PathResolver = context.Server.MapPath;
        }
Ejemplo n.º 31
0
        private static void RegisterTypes(ContainerBuilder builder)
        {
            string baseDirectory = HttpContext.Current.Server.MapPath("~/App_Data") + ConfigurationManager.AppSettings["dataFolderName"];

            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            var repositoryAssemblies = Assembly.Load("FileRepository");
            builder.RegisterAssemblyTypes(repositoryAssemblies).AsImplementedInterfaces().WithParameter(new NamedParameter("path", baseDirectory));

            var serviceAssemblies = Assembly.Load("Services");
            builder.RegisterAssemblyTypes(serviceAssemblies).AsImplementedInterfaces();

            var configurationManagerWrapperAssembly = Assembly.Load("ConfigurationManagerWrapper");
            builder.RegisterAssemblyTypes(configurationManagerWrapperAssembly).AsImplementedInterfaces();

            var fileAssembly = Assembly.Load("SystemFileAdapter");
            builder.RegisterAssemblyTypes(fileAssembly).AsImplementedInterfaces();

            //builder.RegisterType<NLogLogger>().As<ILogger>();
            builder.Register(c => new NLogLogger()).As<ILogger>().InstancePerHttpRequest();
            builder.RegisterType<UserHub>();
            builder.RegisterType<TodoHub>();
            //            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
            builder.RegisterFilterProvider();
        }
        //public static Assembly GetAssembly(string assemblyName)
        //{
        //    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(AppContext.BaseDirectory + $"{assemblyName}.dll");
        //    return assembly;
        //}

        protected override void Load(Autofac.ContainerBuilder builder)
        {
            //注册当前程序集中以“Ser”结尾的类,暴漏类实现的所有接口,生命周期为PerLifetimeScope
            builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerLifetimeScope();
            //注册所有"MyApp.Repository"程序集中的类
            //builder.RegisterAssemblyTypes(GetAssembly("MyApp.Repository")).AsImplementedInterfaces();
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        /// <param name="builder">The builder through which components can be
        /// registered.</param>
        /// <remarks>
        /// Note that the ContainerBuilder parameter is unique to this module.
        /// </remarks>
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            var assemblies = Assembly.GetExecutingAssembly();

            builder.RegisterAssemblyTypes(assemblies).As <IRunAfterEachRequest>().InstancePerRequest();
            builder.RegisterAssemblyTypes(assemblies).As <IRunAtStartup>();
            builder.RegisterAssemblyTypes(assemblies).As <IRunOnEachRequest>().InstancePerRequest();
            builder.RegisterAssemblyTypes(assemblies).As <IRunOnError>();
        }
Ejemplo n.º 34
0
        public void ConfigureContainer(Autofac.ContainerBuilder Cb)
        {
            var A = Assembly.GetExecutingAssembly();

            Cb.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .Where(t => t.Namespace == "")
            .AsImplementedInterfaces().InstancePerLifetimeScope();

            Cb.RegisterAssemblyTypes(A)
            .Where(t => typeof(ControllerBase).IsAssignableFrom(t) && t != typeof(ControllerBase))
            .PropertiesAutowired();
        }
Ejemplo n.º 35
0
        /// <summary>
        /// 创建一个Autofac的Container
        /// </summary>
        /// <returns></returns>
        public static Autofac.IContainer BuildAutofacContainer()
        {
            var builder  = new Autofac.ContainerBuilder();
            var iDao     = Assembly.Load("Log.IDao");
            var dao      = Assembly.Load("Log.Dao");
            var iService = Assembly.Load("Log.IService");
            var service  = Assembly.Load("Log.Service");

            builder.RegisterAssemblyTypes(iDao, dao).Where(t => t.Name.EndsWith("Dao")).AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(iService, service).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();
            return(builder.Build());
        }
Ejemplo n.º 36
0
 protected override void Load(Autofac.ContainerBuilder builder)
 {
     builder.RegisterAssemblyTypes(Assembly.Load("StatTrackr.Data"))
     .Where(t => t.Name.EndsWith("Repository"))
     .AsImplementedInterfaces()
     .InstancePerLifetimeScope();
 }
Ejemplo n.º 37
0
 protected override void Load(Autofac.ContainerBuilder builder)
 {
     builder.RegisterAssemblyTypes(Assembly.Load("CBA.Service"))
     .Where(t => t.Name.EndsWith("Service"))
     .AsImplementedInterfaces()
     .InstancePerLifetimeScope();
 }
Ejemplo n.º 38
0
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            builder.Register((c, p) =>
            {
                var settings = c.Resolve <MongoSettings>();

                return(new MongoClient(settings.ConnectionString));
            }).SingleInstance();

            builder.Register((c, p) =>
            {
                var client   = c.Resolve <MongoClient>();
                var settings = c.Resolve <MongoSettings>();
                var database = client.GetDatabase(settings.Database);

                return(database);
            }).As <IMongoDatabase>();



            var assembly = typeof(MongoModule)
                           .GetTypeInfo()
                           .Assembly;

            builder.RegisterAssemblyTypes(assembly)
            .Where(x => x.IsAssignableTo <IMongoRepository>())
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
        }
Ejemplo n.º 39
0
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            var assembly = typeof(SqlModule).GetTypeInfo().Assembly;

            builder.RegisterAssemblyTypes(assembly).Where(x => x.IsAssignableTo <ISqlRepository>())
            .AsImplementedInterfaces().InstancePerLifetimeScope();
        }
Ejemplo n.º 40
0
 protected override void Load(Autofac.ContainerBuilder builder)
 {
     builder.RegisterAssemblyTypes(this.ThisAssembly)
     .AsClosedTypesOf(typeof(IDefaultRepository <>))
     .AsImplementedInterfaces()
     .InstancePerLifetimeScope();
 }
Ejemplo n.º 41
0
        public static void RegistAll()
        {
            var iocBuilder = new Autofac.ContainerBuilder();

            iocBuilder.RegisterControllers(Assembly.GetExecutingAssembly());
            iocBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //Type baseType = typeof(IH2FBase);
            var iInterfaces = Assembly.Load("H2F.TEST.Interface");
            var implement   = Assembly.Load("H2F.TEST.Implement");

            iocBuilder.RegisterAssemblyTypes(iInterfaces, implement).AsImplementedInterfaces();

            iocBuilder.RegisterType <Student>().As <IPerson>();
            iocBuilder.RegisterType <Worker>().Keyed <IPerson>(PersonType.Worker);

            iocBuilder.RegisterType <Student>().Keyed <IPerson>(PersonType.Student);


            iocBuilder.RegisterType <Log4net>().As <ILogger>();
            var config = GlobalConfiguration.Configuration;

            iocBuilder.RegisterWebApiFilterProvider(config);
            IContainer iocContainer = iocBuilder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(iocContainer);
            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(iocContainer));

            IocContainerManager.SetContanier(iocContainer);
        }
Ejemplo n.º 42
0
        protected void BuildContainer()
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // OPTIONAL: Register model binders that require DI.
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();

            // OPTIONAL: Register web abstractions like HttpContextBase.
            builder.RegisterModule <AutofacWebTypesModule>();

            // OPTIONAL: Enable property injection in view pages.
            builder.RegisterSource(new ViewRegistrationSource());

            // OPTIONAL: Enable property injection into action filters.
            builder.RegisterFilterProvider();

            builder.RegisterAssemblyTypes(typeof(ChangeNameCommandHandler).Assembly).Where(x => x.Name.EndsWith("Handler")).AsImplementedInterfaces();

            RegisterMediatr(builder);

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 43
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var config     = GlobalConfiguration.Configuration;
            var assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
            //注册所有实现了 IDependency 接口的类型
            var baseType = typeof(IDependency);

            builder.RegisterAssemblyTypes(assemblies)
            .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
            .AsSelf().AsImplementedInterfaces()
            .InstancePerLifetimeScope();
            //注册MVC类型
            // builder.RegisterControllers(assemblies).PropertiesAutowired();
            //注册Api类型
            builder.RegisterApiControllers(assemblies);
            //builder.RegisterFilterProvider();
            builder.RegisterWebApiFilterProvider(config);
            var container = builder.Build();

            //注册api容器需要使用HttpConfiguration对象
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            //注册解析
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 44
0
 protected override void Load(Autofac.ContainerBuilder builder)
 {
     //builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
     builder.RegisterAssemblyTypes(Assembly.Load("TaskManagement.Service"))
     .Where(t => t.Name.EndsWith("Service"))
     .AsImplementedInterfaces()
     .InstancePerLifetimeScope();
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Autofac的新添加方法
        /// 用来配置Autofac 服务容器
        /// 配置容器的方法--> 集成Autofac -->由框架自动去调用
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(Autofac.ContainerBuilder builder)
        {
            //Autofac支持批量注册服务(.net core内置的DI不支持, 只能一个一个的注册)
            //程序集扫描注入(包含.Services的类名)
            var assembly = Assembly.GetExecutingAssembly();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .Where(t => t.Namespace == assembly.GetName().Name + ".Services")
            .AsImplementedInterfaces().InstancePerLifetimeScope();

            //给程序集下所有的控制器开启属性注入服务的功能
            builder.RegisterAssemblyTypes(assembly)
            .Where(t => typeof(ControllerBase).IsAssignableFrom(t) && t != typeof(ControllerBase))
            .PropertiesAutowired();

            //给指定的控制器开启属性注入服务的功能
            builder.RegisterType <MessageController>().PropertiesAutowired();
        }
Ejemplo n.º 46
0
        public static void RegisterControllers(params Assembly[] assemblies)
        {
            builder.RegisterControllers(assemblies);
            builder.RegisterAssemblyTypes(typeof(IRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerLifetimeScope();

            container = builder.Build();
        }
Ejemplo n.º 47
0
        public IContainer BuildContainer(Logger log)
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterInstance(log);
            builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).AsImplementedInterfaces();

//            Uncomment for InMemory Storage
//            builder.RegisterAssemblyTypes(typeof(Data.InMemory.Repositories.RecipeRepository).Assembly)
//                   .AsImplementedInterfaces()
//                   .SingleInstance();

            //Uncomment for SQL storage
//            builder.RegisterType<DataContext>().AsSelf().InstancePerRequest();
//            builder.RegisterAssemblyTypes(typeof(Data.SQL.Repositories.RecipeRepository).Assembly).AsImplementedInterfaces().InstancePerRequest();

            //Uncomment for Azure table storage
//            builder.RegisterAssemblyTypes(typeof(PancakeProwler.Data.Table.Repositories.RecipeRepository).Assembly).AsImplementedInterfaces().PropertiesAutowired();

            //Uncomment for Azure DocumentDb storage
//            builder.RegisterAssemblyTypes(typeof(PancakeProwler.Data.DocumentDb.RecipeRepository).Assembly).AsImplementedInterfaces().InstancePerRequest().PropertiesAutowired();

            //Uncomment for storage queue
            //builder.RegisterAssemblyTypes(typeof(PancakeProwler.Data.Queue.Repositories.BookCreationRequestRepository).Assembly).AsImplementedInterfaces().PropertiesAutowired();

            //Uncomment for PostgreSQL storage
            builder.RegisterAssemblyTypes(typeof(PancakeProwler.Data.Postgres.IPostgresRepository).Assembly).AsImplementedInterfaces().InstancePerRequest().PropertiesAutowired();

            builder.RegisterAssemblyTypes(typeof(PancakeProwler.Data.ServiceBus.Repositories.BookCreationRequestRepository).Assembly).AsImplementedInterfaces().PropertiesAutowired();

            builder.RegisterType <PancakeProwler.Data.Common.Repositories.BlobImageRepository>().AsImplementedInterfaces();

            // Uncomment for Elastic Search
            builder.RegisterType <ElasticSearchProvider>().AsImplementedInterfaces();

            // Uncomment for Azure Search
//            builder.RegisterType<AzureSearchProvider>().AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).Where(x => x.Name.EndsWith("Controller")).AsSelf().PropertiesAutowired();
            return(builder.Build());
        }
Ejemplo n.º 48
0
 protected override void Load(Autofac.ContainerBuilder builder)
 {
     try
     {
         builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
         .Where(x => typeof(IJob).IsAssignableFrom(x)).InstancePerDependency();
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Ejemplo n.º 49
0
        public static Autofac.ContainerBuilder AddAppServices(this Autofac.ContainerBuilder builder)
        {
            Assembly appServiceAssembly = Assembly.GetExecutingAssembly();

            builder.RegisterAssemblyTypes(appServiceAssembly)
            .Where(cc => cc.Name.EndsWith("Service")) //筛选具象类(concrete classes)
            .PublicOnly()                             //只要public访问权限的
            .Where(cc => cc.IsClass)                  //只要class型(主要为了排除值和interface类型)
            .AsImplementedInterfaces();               //自动以其实现的所有接口类型暴露(包括IDisposable接口)

            return(builder);
        }
Ejemplo n.º 50
0
        private static IContainer GetConfiguredContainer()
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterAssemblyTypes(typeof(SnapCard).Assembly)
            .Where(t => !t.GetInterfaces().Any(i => i == typeof(ICardOrderingProvider)))
            .AsImplementedInterfaces();

            builder.RegisterType <ShuffleCardOrderingProvider>()
            .AsImplementedInterfaces();

            return(builder.Build());
        }
Ejemplo n.º 51
0
        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();
        }
Ejemplo n.º 52
0
        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 <,>));
        }
Ejemplo n.º 53
0
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            var assembly = typeof(CommandModule)
                           .GetTypeInfo()
                           .Assembly;

            builder.RegisterAssemblyTypes(assembly)
            .AsClosedTypesOf(typeof(ICommandHandler <>))
            .InstancePerLifetimeScope();

            builder.RegisterType <CommandDispatcher>()
            .As <ICommandDispatcher>()
            .InstancePerLifetimeScope();
        }
Ejemplo n.º 54
0
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            Assembly assembly = typeof(ServiceModule).GetTypeInfo().Assembly;

            builder.RegisterAssemblyTypes(assembly)
            .Where(x => x.IsAssignableTo <IService>())
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            // Register Encrypter:
            builder.RegisterType <Encrypter>()
            .As <IEncrypter>()
            .SingleInstance();
        }
Ejemplo n.º 55
0
        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();
        }
Ejemplo n.º 56
0
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            var assembly = typeof(ServiceModule)
                           .GetTypeInfo()
                           .Assembly;

            builder.RegisterAssemblyTypes(assembly)
            .Where(x => x.IsAssignableTo <IService>())
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder.RegisterType <Encrypter>()
            .As <IEncrypter>()
            .SingleInstance();

            builder.RegisterType <JwtHandler>()
            .As <IJwtHandler>()
            .SingleInstance();

            builder.RegisterAssemblyTypes(assembly)
            .Where(x => x.IsAssignableTo <IInputDataBuilder>())
            .SingleInstance();

            var financialSettings = _configuration.GetSettings <FinancialModelingPrepSettings>();

            builder.Register(x => new HttpClient()
            {
                BaseAddress = new Uri(financialSettings.Uri)
            })
            .SingleInstance();

            builder.RegisterAssemblyTypes(assembly)
            .Where(x => x.IsAssignableTo <IValuePredictor>())
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
        }
Ejemplo n.º 57
0
 private void RegisterMediatr(Autofac.ContainerBuilder builder)
 {
     builder.RegisterSource(new ContravariantRegistrationSource());
     builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();
     builder.Register <SingleInstanceFactory>(ctx =>
     {
         var c = ctx.Resolve <IComponentContext>();
         return(t => c.Resolve(t));
     });
     builder.Register <MultiInstanceFactory>(ctx =>
     {
         var c = ctx.Resolve <IComponentContext>();
         return(t => (IEnumerable <object>)c.Resolve(typeof(IEnumerable <>).MakeGenericType(t)));
     });
 }
Ejemplo n.º 58
0
        IContainer InitializeIoC()
        {
            Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            builder.RegisterAssemblyTypes(assemblies)
            .Where(t => !t.Name.StartsWith("System"))
            .AsImplementedInterfaces();
            builder.Register(context => LogManager.GetLogger("BackerUpper")).As <ILogger>();
            builder.Register(context =>
            {
                var config = ConfigurationManager.GetSection("backerUpper");
                return(config as BackerUpper.Configuration.Configuration);
            }).As <BackerUpper.Configuration.IConfiguration>();
            return(builder.Build());
        }
Ejemplo n.º 59
0
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            //注册Service
            var assemblysServices = System.Reflection.Assembly.Load("Webapi.Core.Service");

            builder.RegisterAssemblyTypes(assemblysServices)
            .InstancePerDependency()        //瞬时单例
            .AsImplementedInterfaces()      ////自动以其实现的所有接口类型暴露(包括IDisposable接口)
            .EnableInterfaceInterceptors(); //引用Autofac.Extras.DynamicProxy;

            ////注册Repository
            //var assemblysRepository = Assembly.Load("Webapi.Core.Repository");
            //builder.RegisterAssemblyTypes(assemblysRepository)
            //    .InstancePerDependency()//瞬时单例
            //   .AsImplementedInterfaces()////自动以其实现的所有接口类型暴露(包括IDisposable接口)
            //   .EnableInterfaceInterceptors(); //引用Autofac.Extras.DynamicProxy;
        }
Ejemplo n.º 60
0
        /// <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);
        }