Ejemplo n.º 1
0
        private static IContainer BuildAutofacContainer()
        {
            var builder = new ContainerBuilder();
            var assemblies = GetAssemblies();

            builder.RegisterApiControllers(assemblies);
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

            builder.RegisterType<CommandDispatcher>().As<ICommandDispatcher>().InstancePerRequest();
            //builder.Register(c => new WebApiCommandResolver() as HttpContextBase).As<HttpContextBase>().InstancePerRequest();
            builder.RegisterType<WebApiCommandResolver>().As<ICommandHandlerResolver>().InstancePerRequest();
            builder.RegisterType<JsonEventSerializer>().As<IEventSerializer>().InstancePerRequest();
            builder.RegisterType<MassTransitEventPublisher>().As<IEventPublisher>().SingleInstance();
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<MySqlEventStore>().As<IEventStore>().InstancePerRequest();
            builder.RegisterType<DomainRepository>().As<IDomainRepository>().InstancePerRequest();
            builder.RegisterType<RegisterUserHandler>().As<ICommandHandler<RegisterUserCommand>>().InstancePerRequest();
            builder.RegisterType<RegisterExternalUserHandler>().As<ICommandHandler<RegisterExternalUserCommand>>().InstancePerRequest();

            builder.RegisterType<EncryptionService>().As<IEncryptionService>().InstancePerRequest();
            builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().InstancePerRequest();

            builder.RegisterType<UserApplicationService>().As<IUserApplicationService>().InstancePerRequest();

            builder.RegisterType<UserQueryService>().As<IUserQueryService>().InstancePerRequest();

            SetUpMassTransit(builder);

            IContainer container = builder.Build();

            return container;
        }
Ejemplo n.º 2
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            GlobalConfiguration.Configure(WebApiConfig.Register);

            var config = GlobalConfiguration.Configuration;
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterHubs(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(config);
            builder.RegisterHubs(Assembly.GetExecutingAssembly());
            builder.RegisterInstance(new GameService()).As<IGameService>().SingleInstance();
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var hubConfig = new HubConfiguration();
            hubConfig.Resolver = new AutofacDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.MapSignalR();
        }
Ejemplo n.º 3
0
        protected void SetupDI(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(config);

            builder.RegisterAssemblyTypes(typeof(IRequestHandler<,>).Assembly)
                   .As(type => type.GetInterfaces()
                                   .Where(interfaceType => interfaceType.IsClosedTypeOf(typeof(IRequestHandler<,>)))
                                   .Select(interfaceType => new TypedService(interfaceType)));

            builder.RegisterType<BoxingDbContext>()
                   .InstancePerRequest()
                   .AsSelf()
                   .WithParameter(new TypedParameter(typeof(string), "name=BoxingEntities"));

            builder.RegisterType<PasswordService>()
                   .InstancePerRequest()
                   .As<IPasswordService>();

            builder.RegisterType<AuthorizationService>()
                   .InstancePerRequest()
                   .As<IAuthorizationService>();


            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Ejemplo n.º 4
0
        public static IContainer GetContainer()
        {

            if (_container != null) return _container;

            var containerBuilder = new ContainerBuilder();
            var config = GlobalConfiguration.Configuration;

            // Autofac
            containerBuilder.RegisterModule<AutofacWebTypesModule>();
            containerBuilder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());
            containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();
            containerBuilder.RegisterWebApiFilterProvider(config);

            // register db context
            containerBuilder.RegisterType<YuYanDBContext>()
                .As<IYuYanDBContext>()
                //.WithParameter("connectionString", "YuYanDbAzureContext")
                .InstancePerLifetimeScope();
            // register repository
            containerBuilder.RegisterType<YuYanDBRepository>().AsImplementedInterfaces();
            // register services
            containerBuilder.RegisterType<YuYanService>().AsImplementedInterfaces().InstancePerDependency();

            _container = containerBuilder.Build();
            return _container;
        }
Ejemplo n.º 5
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.º 6
0
        public static IAppBuilder UseAutofacInjection(this IAppBuilder app, HttpConfiguration httpConfiguration)
        {
            var currentAssembly = Assembly.GetExecutingAssembly();

            var builder = new ContainerBuilder();

            // Web API
            builder.RegisterApiControllers(currentAssembly);
            builder.RegisterWebApiFilterProvider(httpConfiguration);

            // MVC
            builder.RegisterControllers(currentAssembly).PropertiesAutowired();

            builder.RegisterModelBinders(currentAssembly);
            builder.RegisterModelBinderProvider();

            builder.RegisterModule<AutofacWebTypesModule>();
            //builder.RegisterSource(new ViewRegistrationSource());

            builder.RegisterFilterProvider();

            builder.RegisterAssemblyModules(currentAssembly);
            
            // Hook it up
            var container = builder.Build();
            httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Register the Autofac middleware FIRST, then the Autofac MVC middleware.
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            return app;
        }
Ejemplo n.º 7
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var config = new HttpConfiguration();
            // Identity Dependencies
            builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerLifetimeScope();
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerLifetimeScope();
            builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication);

            // Web Application Dependencies
            builder.RegisterType<StoreContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<StoreItemService>().AsSelf();
            builder.RegisterType<ReceivingItemService>().AsSelf();

            // Autofac MVC Boilerplate
            builder.RegisterModule<AutofacWebTypesModule>();
            builder.RegisterFilterProvider();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            //Autofac WebAPI2 Boilerplate
            builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();
            app.UseAutofacWebApi(config);
            ConfigureAuth(app);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Registers dependencies for Autofac to resolve via reflection at run-time.
        /// </summary>
        /// <exception cref="Exception"></exception>
        public static void RegisterDependencies()
        {
            // Create the container builder.
            var builder = new ContainerBuilder();

            // Register the Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

            // Register your dependencies.
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
            builder.RegisterType<TekTak.iLoop.UOW.UnitOfWork>().As<TekTak.iLoop.UOW.IUnitOfWork>();
            //builder.RegisterType<iLoopEntity>().InstancePerLifetimeScope();

            ServiceRegister.Register(builder);
            //RegisterJServices(builder);

            AuthorizationRegister.Register(builder);

            ValidatorRegister.Register(builder);

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

            // Create the dependency resolver.
            var resolver = new AutofacWebApiDependencyResolver(container);

            // Configure Web API with the dependency resolver.
            GlobalConfiguration.Configuration.DependencyResolver = resolver;

            FluentValidation.WebApi.FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration,
              provider => provider.ValidatorFactory = new ValidatorFactory(container));
        }
        public static void Initialize()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof (HomeController).Assembly);
            builder.RegisterApiControllers(typeof (AccountController).Assembly);

            builder.RegisterGeneric(typeof (EfRepository<>))
                .As(typeof (IRepository<>))
                .InstancePerRequest();

            builder.RegisterType(typeof (TicketSellingSystemContext))
                .As(typeof (DbContext))
                .InstancePerRequest();

            var assembly = Assembly.GetAssembly(typeof (IUserService));

            builder.RegisterAssemblyTypes(assembly)
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .InstancePerRequest();

            builder.Register(c => new BlockedUserFilter(c.Resolve<IUserService>()))
                .AsWebApiActionFilterFor<ApiController>()
                .InstancePerRequest();
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            var config = GlobalConfiguration.Configuration;
            builder.RegisterWebApiFilterProvider(config);
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Call Autofac DI configurations
               // Bootstrapper.Run();

            var builder = new ContainerBuilder();

            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;

            // Register your Web API controllers.
            //builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterType<ValuesController>().InstancePerRequest();

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Ejemplo n.º 11
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.EnableCors();

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute
                (
                    name: "DefaultApi",
                    routeTemplate: "{controller}/{action}/{id}",
                    defaults: new {id = RouteParameter.Optional}
                );

            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterWebApiFilterProvider(config);
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Ejemplo n.º 12
0
        internal static IContainer BuildRegistrations()
        {
            var builder = new ContainerBuilder();

            // Register our custom dependencies
            builder.RegisterModule(new ServicesModule());

            // Register dependencies in webapi controllers
            builder.RegisterApiControllers(typeof(MvcApplication).Assembly);

            // Register dependencies in filter attributes
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

            // Register autofac's provider for webapi's modelbinders.
            builder.RegisterWebApiModelBinderProvider();

            //Obsolete
            //builder.RegisterWebApiModelBinders(typeof(MvcApplication).Assembly);

            builder.RegisterType<WebApiRequestContextModelBinder>().AsModelBinderForTypes(typeof(RequestContext));

            var container = builder.Build();

            // Set WebApi DI resolver to use our Autofac container
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return container;
        }
Ejemplo n.º 13
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            var config = GlobalConfiguration.Configuration;

            LoadHooks();

            var builder = new ContainerBuilder();

            builder.RegisterModule<AutofacDependencyResolverModule>();
            builder.RegisterModule<CommandModule>();
            builder.RegisterModule<RebusModule>();
            builder.RegisterModule<ValidationModule>();
            builder.RegisterModule<ReadModelConnectionModule>();
            builder.RegisterModule<QueryServiceModule>();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();

            SetupLogger();
            SetupRebus(container);

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
        public override void RegisterComponents(ContainerBuilder builder)
        {
            base.RegisterComponents(builder);
            
            builder.RegisterInstance(this).As<NuGetApiService>();

            var config = ConfigureWebApi();
            builder.RegisterInstance(config).AsSelf();

            builder
                .RegisterApiControllers(GetControllerAssemblies().ToArray())
                .OnActivated(e =>
                {
                    var nugetController = e.Instance as NuGetApiController;
                    if (nugetController != null)
                    {
                        nugetController.Host = Host;
                        nugetController.Service = this;
                        nugetController.Container = Container;
                    }
                })
                .InstancePerApiRequest();

            builder.RegisterWebApiFilterProvider(config);
            builder.RegisterWebApiModelBinderProvider();
        }
Ejemplo n.º 15
0
        public void Configuration(IAppBuilder app)
        {
            var autoFacBuilder = new ContainerBuilder();
            HttpConfiguration config = new HttpConfiguration();

            ConfigureAutoFac(autoFacBuilder);
            autoFacBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            autoFacBuilder.RegisterWebApiFilterProvider(config);
            autoFacBuilder.RegisterWebApiModelBinders(Assembly.GetExecutingAssembly());
            var container = autoFacBuilder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            ConfigureAuth(app);
            WebApiConfig.Register(config);


            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);

            config.EnsureInitialized();

        }
Ejemplo n.º 16
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var builder = new ContainerBuilder();
            var config = new HttpConfiguration();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterType<InstantDeliveryContext>()
                .AsSelf()
                .As<DbContext>() // for UserStore
                .InstancePerLifetimeScope();

            builder.Register(c => new RegularPricingStrategy())
                .AsImplementedInterfaces()
                .SingleInstance();

            RegisterIdentity(app, builder);

            builder.RegisterWebApiFilterProvider(config);

            WebApiConfig.Register(config);

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);

            // has to be called before UseWebApi
            ConfigureOAuth(app);

            app.UseWebApi(config);
        }
Ejemplo n.º 17
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Filters.Add(new ExceptionAttribute());
            config.Filters.Add(new ValidationAttribute());

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Web API routes
            config.MapHttpAttributeRoutes();

            // all routes with ~/api should be resolved by web api
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            #if DEBUG
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            #else
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;
            #endif

            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(config);
            RegisterData(builder);
            RegisterServices(builder);
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.EnsureInitialized();
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        public static void Register()
        {
            var builder = new ContainerBuilder();

            var config = GlobalConfiguration.Configuration;

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterWebApiFilterProvider(config);
            
            //builder.Register(m => new SkillsRepository()).As<ISkillsRepository<Skill>>();
            builder.Register(m => new DiscussionsContext()).As<IDiscussionsContext>();
            builder.Register(m => new DiscussionRepository()).As<IDiscussionRepository<Discussion>>();
            builder.Register(m => new PostRepository()).As<IPostRepository<Post>>();
            builder.Register(m => new InterestsRepository()).As<IInterestsRepository<Interest>>();
            builder.Register(m => new AreasRepository()).As<IAreasRepository<Area>>();
            builder.Register(m => new UsersRepository()).As<IUsersRepository<User>>();
            builder.Register(m => new RssReaderService()).As<IRssReaderService>();
            builder.Register(m => new TwitterService()).As<ITwitterService>();
            
            AutoMapperConfig.RegisterMappings(builder);

            var container = builder.Build();

            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Ejemplo n.º 20
0
        public static void Run()
        {
            var builder = new Autofac.ContainerBuilder();
            var config = GlobalConfiguration.Configuration;
            var service = builder.RegisterType<FormularioService>()
                .As<IFormularioService>();

            var factory = builder.RegisterType<DatabaseFactoryFormulario>()
                .As<IDatabaseFactory>();

            var unit = builder.RegisterType<UnitOfWorkGeneric>()
                .As<IUnitOfWOrkGeneric<IDatabaseFactory>>();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterWebApiFilterProvider(config);

            builder.RegisterWebApiModelBinderProvider();

            service.InstancePerRequest();
            factory.InstancePerRequest();
            unit.InstancePerRequest();


            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.Formatters.Remove(config.Formatters.XmlFormatter);

            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// WebApi的AutoFac配置
        /// </summary>
        /// <param name="projectName">WebApi项目名(命名空间)</param>
        public static void Init_WebApi(string projectName = "")
        {
            //默认项目名称
            projectName = string.IsNullOrEmpty(projectName) ? _DefaultApiName : projectName;
            //构造一个AutoFac的builder容器
            ContainerBuilder builder = new Autofac.ContainerBuilder();
            var configuration        = GlobalConfiguration.Configuration;

            builder.RegisterWebApiFilterProvider(configuration);

            Assembly apicontrollerAss = Assembly.Load(projectName);

            builder.RegisterApiControllers(apicontrollerAss);

            Assembly repositoryAss = Assembly.Load("Services");   //加载数据层程序集。

            Type[] rtypes = repositoryAss.GetTypes();
            builder.RegisterTypes(rtypes)
            .AsImplementedInterfaces().InstancePerApiRequest();

            //创建AutoFac工作容器
            var container = builder.Build();

            configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);//注册api容器
        }
Ejemplo n.º 22
0
        public static void ConfigureContainer()
        {
            var builder = new ContainerBuilder();

            // Register dependencies in controllers
            builder.RegisterControllers(typeof(AutofacConfig).Assembly);

            // Register dependencies in filter attributes
            builder.RegisterFilterProvider();

            // Register dependencies in custom views
            builder.RegisterSource(new ViewRegistrationSource());

            // Register our Data dependencies
            builder.RegisterModule(new Application.Composition.CoreModule());
            builder.RegisterModule(new Application.Composition.ApplicationModule());
            builder.RegisterModule(new Application.Composition.MessagingModule());
            builder.RegisterModule(new PersistenceModule()
            {
                ConnectionStringOrName = "name=ClaimConnectionString"
            });

            var config = GlobalConfiguration.Configuration;
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();

            // Set MVC DI resolver to use our Autofac container
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 23
0
        internal static void Init()
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

            //builder.RegisterInstance<CachedJsonFileStore>(new CachedJsonFileStore()).AsImplementedInterfaces();
            builder.RegisterInstance<InMemoryStore>(new InMemoryStore()).AsImplementedInterfaces();

            //builder.RegisterType<DummyAuthenticator>().AsImplementedInterfaces();
            builder.RegisterType<ActiveDirectoryAuthenticator>().AsImplementedInterfaces();

            builder.RegisterType<AuthorizationFilter>()
                .AsWebApiAuthorizationFilterFor<ReservationController>(c => c.Post(default(Reservation)))
                .InstancePerApiRequest();
            builder.RegisterType<AuthorizationFilter>()
                .AsWebApiAuthorizationFilterFor<ReservationController>(c => c.Put(default(Guid), default(Reservation)))
                .InstancePerApiRequest();
            builder.RegisterType<AuthorizationFilter>()
                .AsWebApiAuthorizationFilterFor<ReservationController>(c => c.Delete(default(Guid)))
                .InstancePerApiRequest();

            GlobalConfiguration.Configuration.DependencyResolver =
                new AutofacWebApiDependencyResolver(builder.Build());
        }
Ejemplo n.º 24
0
        public static IContainer RegisterDependencies(HttpConfiguration httpConfig)
        {
            var builder = new ContainerBuilder();

            // Register your Web API controllers.
            builder.RegisterApiControllers(typeof(BaseWebApiController).Assembly);

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(httpConfig);

            // Register injection types
            builder.RegisterType<QueryProcessor>().AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterType<CommandProcessor>().AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterType<EPDatabase>().As<IEPDatabase>().InstancePerLifetimeScope();

            // Add this so the assembly of the queyrHanderls is know to autofac
            builder.RegisterAssemblyTypes(typeof(GetAccountQueryHandler).Assembly)
                        .Where(t => t.GetInterface(typeof(IQueryHandler<,>).Name) != null)
                        .AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(typeof(CreateEvaluationTemplateCommandHandler).Assembly)
                .Where(t => t.GetInterface(typeof(ICommandHandler<>).Name) != null)
                .AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(typeof(CreateStudyPlanCommandHandler).Assembly)
                      .Where(t => t.GetInterface(typeof(ICommandHandler<,>).Name) != null)
                      .AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope();

            IContainer container = builder.Build();
            //DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container));
            //GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return container;
        }
Ejemplo n.º 25
0
        private void CreateContainer(HttpConfiguration configuration,IApplicationHost applicationHost,IConfigurationProvider configurationProvider)
        {
            var assemblies          = applicationHost.Assemblies.ToArray();
            var containerBuilder    = new ContainerBuilder();

            containerBuilder.RegisterModelBinderProvider();
            //containerBuilder.RegisterFilterProvider(); TODO: Seems to be an autofac MVC4 integration issue
            containerBuilder.RegisterModelBinders(assemblies);
            containerBuilder.RegisterApiControllers(assemblies);
            containerBuilder.RegisterControllers(assemblies);
            containerBuilder.RegisterWebApiFilterProvider(configuration);
            containerBuilder.RegisterWebApiModelBinders(assemblies);
            containerBuilder.RegisterModule(new AutofacWebTypesModule());

            containerBuilder.RegisterAssemblyModules(assemblies);
            containerBuilder.RegisterAssemblyTypes(assemblies).Where(t => t.IsAssignableTo<IRouteProvider>()).As<IRouteProvider>();
            containerBuilder.RegisterAssemblyTypes(assemblies).Where(t => t.IsAssignableTo<IBootTask>()).As<IBootTask>();
            containerBuilder.RegisterAssemblyTypes(assemblies).Where(t => t.IsAssignableTo<AreaRegistration>()).As<AreaRegistration>();

            containerBuilder.RegisterInstance(applicationHost).As<IApplicationHost>();
            containerBuilder.RegisterInstance(configurationProvider).As<IConfigurationProvider>();

            var container = containerBuilder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            SignalR.GlobalHost.DependencyResolver = new AutofacSignalRDependencyResolver(container);
        }
Ejemplo n.º 26
0
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();

            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            RegisterDependencies(builder);

            // Set the dependency resolver to be Autofac.
            IContainer container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        public static void Config()
        {
            var builder = new ContainerBuilder();

            // Register dependencies in controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // Register dependencies in filter attributes
            builder.RegisterFilterProvider();

            // Register dependencies in custom views
            builder.RegisterSource(new ViewRegistrationSource());

            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;

            // Register your Web API controllers.
            builder.RegisterApiControllers(typeof(ReservationController).Assembly);

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            builder.RegisterModule(new ManagerModule());

            var container = builder.Build();
            var webApiResolver = new AutofacWebApiDependencyResolver(container);
            // Mechanism for setting the dependency resolver for Web API and MVC is different.
            // Web API uses GlobalConfiguration.Configuration.DependencyResolver
            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            var mvcResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(mvcResolver);
        }
Ejemplo n.º 28
0
        public static IContainer Configure(HttpConfiguration config, IOpenIdClientStore store) {

            var builder = new ContainerBuilder();
            builder
                .RegisterType<AutoMapperConfig>()
                .As<IAutoMapperFactory>();

            builder
                .RegisterType<OpenIdClientRegistrationService>()
                .As<IOpenIdClientRegistrationService>();

            builder
                .RegisterType<OpenIdClientRegistrationValidator>()
                .As<IOpenIdClientRegistrationValidator>();

            builder.RegisterInstance(store);

            //httpConfig.Filters.Add(new UnhandledExceptionFilter()); -- logging?

            builder.RegisterApiControllers(typeof(AutofacConfig).Assembly);
            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return container;
        }
        public static IContainer Initialize(ContainerBuilder builder, HttpConfiguration config)
        {
            // Register all controllers
            builder.RegisterApiControllers(typeof(Startup).Assembly);

            // Register Autofac filter provider
            builder.RegisterWebApiFilterProvider(config);

            // Register model binders
            builder.RegisterWebApiModelBinderProvider();

            // Register all Autofac specific IModule implementations
            builder.RegisterAssemblyModules(typeof(Startup).Assembly);
            builder.RegisterAssemblyModules(typeof(AutofacMediator).Assembly);

            builder.RegisterModule(new RequestHandlerModule());
            builder.RegisterModule(new EntityFrameworkModule());
            builder.RegisterModule(new DocumentGeneratorModule());

            // http://www.talksharp.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc-5
            builder.RegisterType<IwsIdentityContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>().InstancePerRequest();

            return builder.Build();
        }
Ejemplo n.º 30
0
        public static IContainer ConfigureContainer(this IAppBuilder app, HttpConfiguration config, IReadOnlyCollection<Assembly> applicationAssemblies, IEnumerable<Module> dependencyModules, WebOption webOption)
        {
            var builder = new ContainerBuilder();

            foreach (var module in dependencyModules)
                builder.RegisterModule(module);

            var assemblies = applicationAssemblies.ToArray();

            ConfigureContainer(builder, webOption, assemblies);

            if (webOption.UseApi)
                builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();

            if (webOption.UseApi)
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            if (webOption.UseMvc)
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            app.UseAutofacMiddleware(container);

            if (webOption.UseApi)
                app.UseAutofacWebApi(config);

            return container;
        }
Ejemplo n.º 31
0
        protected void Application_Start()
        {
            var config = GlobalConfiguration.Configuration;

            config.MapHttpAttributeRoutes();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            config.Filters.Add(new BadRequestExceptionAttribute());
            config.Filters.Add(new NotFoundExceptionAttribute());
            config.Filters.Add(new AuthAttribute());
            config.Filters.Add(new ValidationFilterAttribute());

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterFilters(config);

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(config);

            RegisterHandlers(builder);
            RegisterContext(builder);

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            FluentValidationModelValidatorProvider.Configure(config);

            config.EnsureInitialized();

            TestsContext.SetInitializer();
            ConfigureMappings();
        }
Ejemplo n.º 32
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.º 33
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute("DefaultApi",
                "api/{controller}/{id}",
                new {id = RouteParameter.Optional}
                );

            var builder = new ContainerBuilder();

            builder.RegisterType<ConsoleLogger>().As<ILogger>();

            builder.Register(c => new LoggingActionFilter(c.Resolve<ILogger>())).
                AsWebApiActionFilterFor<ValuesController>(c => c.Get())
                .InstancePerRequest();

            var globalConfiguration = GlobalConfiguration.Configuration;
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Ejemplo n.º 34
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Autofac
            // Create the container builder.
            var builder = new ContainerBuilder();

            // Register the Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
            // Register other dependencies.
            //builder.Register(c => new Logger()).As<ILogger>().InstancePerApiRequest();

            // Build the container.
            IContainer container = builder.Build();

            // Create the depenedency resolver.
            //var resolver =

            // Configure Web API with the dependency resolver.
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); ;
        }
Ejemplo n.º 35
0
        protected void Application_Start()
        {
            var config = GlobalConfiguration.Configuration;


            // Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());


            builder.RegisterModule(new RepositoryModule());
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());

            // Register your Web API controllers.

            builder.RegisterApiControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
            //OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            //OPTIONAL: Register the Autofac model binder provider.
            builder.RegisterWebApiModelBinderProvider();

            //Set the dependency resolver to be Autofac.


            var container = builder.Build();

            //  DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container));

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            config.DependencyResolver =
                new AutofacWebApiDependencyResolver(container);



            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.EnsureInitialized();
        }
Ejemplo n.º 36
0
    public void Configure(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();

        config.MapHttpAttributeRoutes();                                                      // using attribute based routing because I prefer it

        var builder = new Autofac.ContainerBuilder();

        // Authentication Filter
        builder.Register(c => new AuthoriseAttribute())
        .AsWebApiAuthenticationFilterFor <StatsController>()
        .InstancePerLifetimeScope();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); // Create the container builder.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());                       // Register the Web API controllers.
        builder.RegisterWebApiFilterProvider(config);                                          // optional

        builder.RegisterType <Stat>().As <IStat>().InstancePerRequest();


        var container = builder.Build();

        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        appBuilder.UseAutofacMiddleware(container);
        appBuilder.UseAutofacWebApi(config);                                                  // Make sure the Autofac lifetime scope is passed to Web API.
        appBuilder.UseWebApi(config);                                                         // enable web-api


        string filedir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "../../web");

        appBuilder.UseFileServer(new FileServerOptions
        {
            EnableDefaultFiles  = true,
            DefaultFilesOptions =
            {
                DefaultFileNames = new[] { "Index.html" }
            },
            EnableDirectoryBrowsing = true,
            FileSystem = new PhysicalFileSystem(filedir),
        });
    }
Ejemplo n.º 37
0
        public static void ConfigureContainer()
        {
            var builder = new Autofac.ContainerBuilder();
            var config  = GlobalConfiguration.Configuration;

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // controller
            builder.RegisterWebApiFilterProvider(config);                    // filter

            builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration);
            builder.Register(e => // HttpContextBase
                             HttpContext.Current != null
                        ? new HttpContextWrapper(HttpContext.Current)
                        : e.Resolve <HttpRequestMessage>().Properties["MS_HttpContext"])
            .As <HttpContextBase>()
            .InstancePerRequest();


            builder.RegisterModule(new ServiceModule()); // Moduel
            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Ejemplo n.º 38
0
        public static void Register()
        {
            var builder = new Autofac.ContainerBuilder();

            var config = GlobalConfiguration.Configuration;

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            // OPTIONAL: Register the Autofac model binder provider.
            builder.RegisterWebApiModelBinderProvider();


            builder.RegisterModule(new EFModule());
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new RepositoryModule());

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Ejemplo n.º 39
0
 public InProcServicesContainerBuilder WithHttpConfig(HttpConfiguration config)
 {
     containerBuilder.RegisterWebApiFilterProvider(config);
     return(this);
 }