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();
        }
        public ConfigureContainer(Action<IContainer> registerResolver)
        {
            var builder = new ContainerBuilder();

            // load module in plugin folder (if have)
            foreach (var referencedPlugin in PreApplicationInit.ReferencedPlugins)
            {
                builder.RegisterAssemblyModules(referencedPlugin);
            }

            // load all modules in bin folder
            var assemblies = AssemblyHelper.GetDllsInPath(HostingEnvironment.MapPath("~/bin/"));
            foreach (var assembly in assemblies)
            {
                builder.RegisterAssemblyModules(assembly);
            }

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            //builder.Register(c => new Logger()).As<ILogger>().InstancePerHttpRequest();
            builder.RegisterFilterProvider();

            _container = builder.Build();

            registerResolver(_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));
        }
Beispiel #4
0
 public void Initialize()
 {
     var containerBuilder = new ContainerBuilder();
     containerBuilder.RegisterAssemblyModules(typeof(RtmpStream).Assembly);
     containerBuilder.RegisterAssemblyModules(typeof(DrNuClient).Assembly);
     containerBuilder.RegisterAssemblyModules(typeof(Bootstrapper).Assembly);
     Container = containerBuilder.Build();
 }
Beispiel #5
0
        static TestEnvironment()
        {
            var builder = new ContainerBuilder();
            builder.RegisterAssemblyModules(typeof(LightCompiler).Assembly);
            builder.RegisterAssemblyModules(typeof(LightProcessor).Assembly);

            Container = builder.Build();
        }
Beispiel #6
0
 private static IServiceController BuildServiceController()
 {
     var containerBuilder = new ContainerBuilder();
     containerBuilder.RegisterAssemblyModules(typeof(ServiceModule).Assembly);
     containerBuilder.RegisterAssemblyModules(typeof(DomainModule).Assembly);
     Container = containerBuilder.Build();
     
     return Container.Resolve<IServiceController>();
 }
Beispiel #7
0
        private static void RegisterContainer(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();
            var webAssembly = Assembly.GetExecutingAssembly();

            builder.RegisterApiControllers(webAssembly);
            builder.RegisterAssemblyModules(typeof(ICodeProcessor).Assembly);
            builder.RegisterAssemblyModules(webAssembly);

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Beispiel #8
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;

            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterAssemblyModules(typeof(ApplicationModule).Assembly);
            containerBuilder.RegisterAssemblyModules(typeof(PresentationModule).Assembly);

            Container = containerBuilder.Build();
            var controller = Container.Resolve<IApplicationController>();
            controller.Start();
        }
        internal static void RegisterIoc()
        {
            var builder = new ContainerBuilder();

            // Register your service implementations.
            builder.RegisterType<EmployeeService>().SingleInstance();

            builder.RegisterAssemblyModules(Assembly.Load("Employee.DataAccess"));
            builder.RegisterAssemblyModules(Assembly.Load("Employee.BusinessLogic"));
            builder.RegisterAssemblyModules(Assembly.Load("Employee.Mapping"));

            // Set the dependency resolver.
            var container = builder.Build();
            AutofacHostFactory.Container = container;
        }
        public static void Bootstrap(Assembly entryAssembly)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(entryAssembly);
            builder.RegisterLifetimeHubManager();
            builder.RegisterHubs(entryAssembly);
            builder.RegisterAssemblyModules(typeof(DependencyInjectionConfiguration).Assembly);
            builder.RegisterAssemblyModules(entryAssembly);

            var container = builder.Build();

            GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(container));
        }
Beispiel #11
0
 internal IContainer CreateContainer()
 {
     var builder = new ContainerBuilder();
     // Registers all modules
     builder.RegisterAssemblyModules(GetType().GetTypeInfo().Assembly);
     return builder.Build();
 }
        protected override void ConfigureLifetimeScope(ContainerBuilder builder)
        {
            base.ConfigureLifetimeScope(builder);

            foreach (var endpointSpecificationType in _registration.EndpointSpecificationTypes)
            {
                builder.RegisterType(endpointSpecificationType)
                    .As<IEndpointSpecification>();
            }

            builder.RegisterAssemblyTypes(_registration.Assembly)
                .Where(x => x.HasInterface<IConsumer>())
                .AsSelf();

            builder.RegisterType(_registration.ServiceSpecificationType)
                .As<IServiceSpecification>();

            builder.RegisterType<AssemblyBusServiceConfigurator>()
                .As<IBusServiceConfigurator>();

            builder.RegisterAssemblyModules(_registration.Assembly);

            builder.RegisterType<FileConfigurationProvider>()
                .WithParameter(TypedParameter.From(_registration.Assembly))
                .As<IConfigurationProvider>()
                .SingleInstance();

            builder.RegisterModule<ConfigurationProviderModule>();
        }
Beispiel #13
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()));
        }
Beispiel #14
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureLogger();

            var builder = new ContainerBuilder();
            builder.RegisterLogger();
            builder.RegisterByAttributes(typeof (Startup).Assembly);
            builder.RegisterAssemblyModules(typeof (Startup).Assembly);
            builder.RegisterHubs(typeof (Startup).Assembly);
            var container = builder.Build();

            // config hubs
            var config = new HubConfiguration();
            config.Resolver = new AutofacDependencyResolver(container);

            app.UseJwtTokenAuthentication(container.Resolve<IssuerSetting>(),
                                          container.Resolve<AudienceSetting>(),
                                          container.Resolve<ClientSecretSetting>(),
                                          container.Resolve<ICurrentUserProvider>());

            app.MapSignalR(config);

            app.UseNancy(new NancyOptions
            {
                Bootstrapper = new NancyBootstrapper(container)
            });
            app.UseStageMarker(PipelineStage.MapHandler);
            app.UseCors(CorsOptions.AllowAll);

            JsonSettings.RetainCasing = false;

            SeedData(container);
        }
 public static void Run()
 {
     var c = new ContainerBuilder();
     c.RegisterAssemblyModules(typeof (ConfigTask_1_Container).Assembly);
     StaticConfig.Container = c.Build();
     DependencyResolver.SetResolver(new AutofacDependencyResolver(StaticConfig.Container));
 }
Beispiel #16
0
        public static void Register()
        {
            var cb = new Autofac.ContainerBuilder();

            cb.RegisterType <QuizDbContext>().InstancePerRequest();
            cb.RegisterType <Repo <Quiz> >().As <IRepo <Quiz> >().InstancePerRequest();
            cb.RegisterType <Repo <Question> >().As <IRepo <Question> >().InstancePerRequest();
            cb.RegisterType <Repo <Answer> >().As <IRepo <Answer> >().InstancePerRequest();
            cb.RegisterType <Repo <QuizCategory> >().As <IRepo <QuizCategory> >().InstancePerRequest();
            cb.RegisterType <Repo <QuizRating> >().As <IRepo <QuizRating> >().InstancePerRequest();
            cb.RegisterType <Repo <QuizResult> >().As <IRepo <QuizResult> >().InstancePerRequest();
            cb.RegisterType <Repo <ContactInfo> >().As <IRepo <ContactInfo> >().InstancePerRequest();
            cb.RegisterType <Repo <UserActivity> >().As <IRepo <UserActivity> >().InstancePerRequest();

            cb.RegisterType <QuizService>().As <IQuizService>().InstancePerRequest();
            cb.RegisterType <QuestionService>().As <IQuestionService>().InstancePerRequest();
            cb.RegisterType <AnswerService>().As <IAnswerService>().InstancePerRequest();
            cb.RegisterType <QuizCategoryService>().As <IQuizCategoryService>().InstancePerRequest();
            cb.RegisterType <QuizResultService>().As <IQuizResultService>().InstancePerRequest();
            cb.RegisterType <UserActivityService>().As <IUserActivityService>().InstancePerRequest();

            cb.RegisterType <ModelConverter>().InstancePerRequest();
            cb.RegisterType <ViewModelConverter>().InstancePerRequest();

            cb.RegisterControllers(typeof(MvcApplication).Assembly).InstancePerRequest();
            cb.RegisterType <AccountController>().InstancePerDependency();
            cb.RegisterAssemblyModules(typeof(MvcApplication).Assembly);

            var container = cb.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #17
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            Log.Logger = new LoggerConfiguration()
                .Destructure.UsingAttributes()
                .Enrich.WithCallerInformation()
                .ReadFrom.AppSettings()
                .CreateLogger();
            
            GlobalConfiguration.Configuration
                .UseSqlServerStorage(
                "NonProcessingDay",
                new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) });

            GlobalConfiguration.Configuration.UseLogProvider(new SerilogLogProvider());
            var Container = new ContainerBuilder();
            Container.RegisterAssemblyModules(typeof(MvcApplication).Assembly);

            
            iContainer = Container.Build();
            GlobalConfiguration.Configuration.UseAutofacActivator(iContainer);
           
        }
Beispiel #18
0
 public static void Configure()
 {
     var builder = new ContainerBuilder();
     builder.RegisterAssemblyModules(typeof (ContainerConfig).Assembly);
     var container = builder.Build();
     DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
 }
Beispiel #19
0
        protected void Application_Start()
        {
            //GlobalHost.DependencyResolver.UseRedis("127.0.0.1", 6379, string.Empty, "AgileR");

            AreaRegistration.RegisterAllAreas();

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

            var builder = new ContainerBuilder();
            builder.RegisterModule<AutofacWebTypesModule>();
            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());
            var container = builder.Build();

            var autofacDependencyResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(autofacDependencyResolver);
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;

            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
                IncludeErrorDetailPolicy.Always;

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //GlobalConfiguration.Configuration.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            GlobalConfiguration.Configuration.EnableSystemDiagnosticsTracing();
        }
        public static IContainer Initialize(ContainerBuilder builder)
        {
            // Register all controllers
            builder.RegisterControllers(typeof(Startup).Assembly)
                .OnActivating(e =>
                {
                    var controller = (Controller)e.Instance;
                    controller.TempDataProvider = new CookieTempDataProvider();
                });

            // Register model binders
            builder.RegisterModelBinders(typeof(Startup).Assembly);
            builder.RegisterModelBinderProvider();

            // Register all HTTP abstractions
            builder.RegisterModule<AutofacWebTypesModule>();

            //Register mapper module
            builder.RegisterModule(new MappingModule());

            // Allow property injection in views
            builder.RegisterSource(new ViewRegistrationSource());

            // Allow property injection in action filters
            builder.RegisterFilterProvider();

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

            return builder.Build();
        }
        public static ContainerBuilder Configure(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // make the RavenDB document store a single instance for the lifetime of the app
            builder.Register(c =>
            {
                return new UserDb().DbContext;
            }).As<IDocumentStore>().SingleInstance();

            // ensure a new Raven Session is created from the RavenDB document store when an IAysncDocumentSession dependency is resolved/injected
            builder.Register(c =>
            {
                var ravenSession = c.Resolve<IDocumentStore>().OpenAsyncSession();

                ravenSession.Advanced.UseOptimisticConcurrency = true;

                return ravenSession;
            }).As<IAsyncDocumentSession>();

            // ensure a new instance of a RavenUserStore<ApplicationUser> is created with an async Raven Session when an IUserStore<ApplicationUser> dependency is resolved/injected
            builder.Register(c => new RavenUserStore<ApplicationUser>(c.Resolve<IAsyncDocumentSession>(), disposeDocumentSession: false)).As<IUserStore<ApplicationUser>>();

            // ensure a new instance of the AuthenicationManager that is reqistered in the OwinContext is created when an IAuthenticationManager dependency is resolved/injected
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).As<IAuthenticationManager>();

            // ensure a new instance of a UserIdentityService is created with resolved dependencies when an IUserIdentityService dependency is resolved/injected
            builder.Register(c => new UserIdentityService(c.Resolve<IUserStore<ApplicationUser>>(), c.Resolve<IAuthenticationManager>())).As<IUserIdentityService>();

            // ensure any custom Autofac modules are registered found in this assembly
            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

            return builder;
        }
 public static void BuildContainer()
 {
     var builder = new ContainerBuilder();
     ConfigureBlackJackGameDependencies();
     builder.RegisterAssemblyModules(ThisAssembly);
     Container = builder.Build();
 }
        public static void RegisterAutoFac()
        {
            var builder = new ContainerBuilder();

            // MVC
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());

            // WebApi
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterModule<AutofacWebTypesModule>();

            // Register services
            AddRegistrations(builder);
            var container = builder.Build();

            // Set the dependency resolver for Web API.
            var webApiResolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            // Set the dependency resolver for MVC.
            var mvcResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(mvcResolver);
        }
Beispiel #24
0
        public Container(IServiceCollection services)
        {
            // Create the container builder.
            autofacContainerBuilder = new Autofac.ContainerBuilder();

            // Register dependencies, populate the services from
            // the collection, and build the container. If you want
            // to dispose of the container at the end of the app,
            // be sure to keep a reference to it as a property or field.
            //builder.RegisterType<MyType>().As<IMyTyHippe>();

            //If nothing is using/calling a type in an assembly you are trying to load,
            //Load(...) will fail. The compiler will optimize the code so that unused dependencies
            //are removed.

            var assembly = Assembly.Load(new AssemblyName {
                Name = "Authentication.Container"
            });

            autofacContainerBuilder.RegisterAssemblyModules(assembly);

            autofacContainerBuilder.Populate(services);
            autofacContainer = autofacContainerBuilder.Build();

            serviceProvider = new AutofacServiceProvider(autofacContainer);
        }
        /// <summary>
        ///     Windsor installer install method
        /// </summary>
        public static void Register(ref ContainerBuilder builder)
        {
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

            builder.Register(c => new MapperConfiguration(cfg =>
            {
                foreach (var profile in c.Resolve<IEnumerable<Profile>>())
                {
                    cfg.AddProfile(profile);
                }
            })).AsSelf().SingleInstance();

            //register the mapper
            builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(
                Assembly.GetExecutingAssembly())
                    .Where(type => ((type.Name.EndsWith("Services") ||
                                    type.Name.EndsWith("Resolver") ||
                                    type.Name.EndsWith("Helper") ||
                                    type.Name.EndsWith("Mapper") ||
                                    type.Name.EndsWith("Controller")) && type.IsClass) ||
                                  (!type.IsAbstract && typeof(ApiController).IsAssignableFrom(type)))
                    .AsImplementedInterfaces()
                    .InstancePerRequest();

            builder.RegisterType<WebApiSeedDbInitializer>().As<IDatabaseInitializer<WebApiSeedDbContext>>().AsImplementedInterfaces()
                    .InstancePerRequest();
        }
Beispiel #26
0
        private static IContainer GetContainer()
        {
            var container = new Autofac.ContainerBuilder();

            container.RegisterAssemblyModules(Assembly.Load("ToolkitSample.DataAccess"));
            return(container.Build());
        }
Beispiel #27
0
        private static int RunService()
        {
            var builder = new ContainerBuilder();

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

            var exitCode = HostFactory.Run(
                x =>
                {
                    var container = builder.Build();

                    x.UseAutofacContainer(container);

                    x.UseSerilog();

                    var serviceConfiguration = container.Resolve<ITopshelfConfiguration>();

                    x.SetServiceName(serviceConfiguration.ServiceName);
                    x.SetDescription(serviceConfiguration.ServiceDescription);
                    x.SetDisplayName(serviceConfiguration.ServiceDisplayName);

                    x.Service<ServiceRunner>(
                        s =>
                        {
                            s.ConstructUsingAutofacContainer();
                            s.WhenStarted(i => i.Start());
                            s.WhenStopped(i => i.Stop());
                        });
                });

            return (int)exitCode;
        }
Beispiel #28
0
        public static void Configure()
        {
            var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
            var builder = new ContainerBuilder();

            builder.RegisterAssemblyTypes(assemblies)
                .Where(t => typeof(IStartable).IsAssignableFrom(t))
                .As<IStartable>()
                .SingleInstance();

            builder.RegisterAssemblyModules(assemblies);

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var container = builder.Build();

            // Set the dependency resolver for Web API.
            var webApiResolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            // Set the dependency resolver for MVC.
            var mvcResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(mvcResolver);
        }
        public static void Init()
        {
            var builder = new ContainerBuilder();

            // Register your MVC controllers.
            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();

            // grab all the modules (available here) and register them
            builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #30
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;
        }
        public static void Initialize(Assembly webAssembly, IEnumerable<Assembly> relatedAssemblies)
        {
            var builder = new ContainerBuilder();

            // register all of autofac modules
            builder.RegisterAssemblyModules(relatedAssemblies.ToArray());

            // register all controllers
            builder.RegisterControllers(webAssembly);

            // register all web api controllers
            builder.RegisterApiControllers(webAssembly);

            // register all filters
            builder.RegisterFilterProvider();

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

            // register it to ASP.NET MVC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

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

            // Configure Web API with the dependency resolver.
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
Beispiel #32
0
        /// <summary>
        /// Configuration routine of the autofac container.
        /// </summary>
        /// <param name="eventBus">The event bus.</param>
        /// <param name="hoardeManager">The hoarde manager.</param>
        /// <param name="configurationManager">The host's configuration manager.</param>
        public static void Configure(IEventBus eventBus, ServiceModel.IHoardeManager hoardeManager, INutConfiguration configurationManager)
        {
            var builder = new ContainerBuilder();

            builder.RegisterInstance(eventBus);
            builder.RegisterInstance(hoardeManager);
            builder.RegisterInstance(configurationManager);

            builder.RegisterType<ServiceModel.ServicesManager>().AsImplementedInterfaces().SingleInstance();
            builder.RegisterType<ServiceModel.PollingClientCollection>().AsSelf().SingleInstance();
            builder.RegisterType<ServiceModel.RegisteredPackagesPollingClient>().AsSelf().SingleInstance();
            builder.RegisterType<ServiceModel.ReleasesPollingClient>();
            builder.RegisterType<ConfigurationManagement.DbConfigurationSettings>();

            // we will apply most of the configuration in one or more assembly modules.
            builder.RegisterAssemblyModules(typeof(AutofacConfig).Assembly);

            switch (configurationManager.Mode)
            {
                case ExecutionMode.Development:
                    builder.RegisterType<Repositories.OnDisk.OnDiskPackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
                    break;
                case ExecutionMode.Production:
                    builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
                    break;
                default:
                    builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
                    _log.WarnFormat("Unknown execution mode '{mode}'.  Registered Sqlite Repository.", configurationManager.Mode);
                    break;
            }

            _container = builder.Build();
        }
        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;
        }
Beispiel #34
0
        // Methods
        public void ConfigureContainer(Autofac.ContainerBuilder builder)
        {
            #region Contracts

            if (builder == null)
            {
                throw new ArgumentException(nameof(builder));
            }

            #endregion

            // Module
            builder.RegisterAssemblyModules(Assembly.GetEntryAssembly());
        }
Beispiel #35
0
        public static void RegisterServiceLocator()
        {
            var builder = new Autofac.ContainerBuilder();

            // Registers modules
            var assemblies = BuildManager.GetReferencedAssemblies().Cast <Assembly>();

            builder.RegisterAssemblyModules(assemblies.ToArray());

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

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
 public static void RegisterAssemblyModules(this ContainerBuilder builder, params Assembly[] assemblies)
 {
     builder.RegisterAssemblyModules <IModule>(assemblies);
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Maintain property names during serialization. See:
            // https://github.com/aspnet/Announcements/issues/194
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options =>
                            options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            ;

            ConfigureRazorAndCompression(services);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSignalR();

            // Add Kendo UI services to the services container
            services.AddKendo();

            // services.AddScoped<NLoggingAttribute>();

            services.AddAutoMapper();

            services.AddHostedService <TimedHostedService>();

            services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.AccessDeniedPath  = new PathString("/AccessDenied");
                options.LoginPath         = new PathString("/UserAccount");
                options.ExpireTimeSpan    = TimeSpan.FromSeconds(60000);
                options.SlidingExpiration = true;

                options.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToAccessDenied = (ctx) =>
                    {
                        var request = ctx.HttpContext.Request.Path;
                        _logger.LogError("Access Denied to Path" +
                                         request.Value);
                        ctx.Response.Redirect(ctx.RedirectUri);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromDays(60);
                options.ExcludedHosts.Add("example.com");
                options.ExcludedHosts.Add("www.example.com");
            });

            services.AddAntiforgery(options =>
            {
                // new API
                options.Cookie.Name = "AntiforgeryCookie";

                options.Cookie.Path         = "/";
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            });

            services.AddHttpsRedirection(options =>
            {
                options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                options.HttpsPort          = 443;
            });

            ConfigureMiniProfier(services);

            ConfigureWebOptimer(services);

            var builder = new Autofac.ContainerBuilder();

            builder.RegisterAssemblyModules(System.Reflection.Assembly.GetExecutingAssembly());
            builder.Populate(services);

            var sqlConnection = Configuration.GetValue <string>("DBConnection");

            builder.RegisterModule(new ServiceDIContainer(sqlConnection));

            builder.Register(c =>
            {
                return(Bus.Factory.CreateUsingRabbitMq(sbc =>
                                                       sbc.Host(new Uri("rabbitmq://localhost:/"), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                })

                                                       ));
            })
            .As <IBusControl>()
            .As <IBus>()
            .As <IPublishEndpoint>()
            .SingleInstance();

            this.ApplicationContainer = builder.Build();

            return(new AutofacServiceProvider(this.ApplicationContainer));
        }