Exemple #1
0
        public void Initialise(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerLifetimeScope();
            builder.RegisterFilterProvider();

            const string nameOrConnectionString = "name=FamilyTreeDbConnection";

            builder.Register <IDbContext>(b =>
            {
                var logger  = b.ResolveOptional <ILogger>();
                var context = new FamilyTreeDbContext(nameOrConnectionString, logger);
                return(context);
            }).InstancePerLifetimeScope();

            builder.Register(b => NLogLogger.Instance).SingleInstance();

            builder.RegisterModule <RepositoryCapsuleModule>();
            builder.RegisterModule <ServiceCapsuleModule>();
            builder.RegisterModule <ControllerCapsuleModule>();

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            var resolver = new AutofacWebApiDependencyResolver(container);

            config.DependencyResolver = resolver;
        }
Exemple #2
0
    public static void Start()
    {
        var builder = new ContainerBuilder();

        builder.RegisterGlassServices();
        builder.RegisterCacheServices();
        builder.RegisterProcessors(Assembly.Load("YOURPROJECT.Library"));
        builder.RegisterGlassMvcServices("YOURPROJECT.Web");
        builder.RegisterGlassFactory("YOURPROJECT.Library");
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        // Module registrations
        builder.RegisterModule(new MiniProfilerModule("YOURPROJECT.Library", "YOURPROJECT.Web"));
        builder.RegisterModule(new LogInjectionModule<ILog>(LogManager.GetLogger);

        // Custom Registrations

        // This is necessary to 'seal' the container, and make it resolvable from the AutofacStartup.ServiceLocator singleton
        IContainer container = builder.Build();
        container.RegisterContainer();

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

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

        // Configure the MVC dependency resolver
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
Exemple #3
0
        public static void Register(HttpConfiguration config, AutofacWebApiDependencyResolver resolver)
        {
            config.MapHttpAttributeRoutes();

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

            config.DependencyResolver = resolver;

            ConfigureFormatters(config);

            config.EnableSwagger("docs/auth/api/{apiVersion}/", c =>
            {
                var baseDirectory    = AppDomain.CurrentDomain.BaseDirectory;
                var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";
                var commentsFile     = Path.Combine(baseDirectory, commentsFileName);

                c.IncludeXmlComments(commentsFile);
                c.DescribeAllEnumsAsStrings();
                c.SingleApiVersion("v1", "TaskCat Auth Api");
            }).EnableSwaggerUi("docs/auth/{*assetPath}");
        }
        public static void Initialize(HttpConfiguration config, IContainer container)
        {
            var dependencyResolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver;
            config.DependencyResolver = dependencyResolver;
        }
Exemple #5
0
        public static void RegisterAutofac()
        {
            var builder = new ContainerBuilder();

            //Implement the specific injectors for Data and the view models
            builder.RegisterType <AdventureWorks>().AsSelf().As <DbContext>()
            .PropertiesAutowired().InstancePerLifetimeScope();

            builder.RegisterType <ProductsViewModel>().AsSelf().As <ProductsViewModel>()
            .PropertiesAutowired().InstancePerLifetimeScope();

            // Register your Web API controllers
            builder.RegisterApiControllers(typeof(ConstantsController).Assembly);
            builder.RegisterApiControllers(typeof(ProductsController).Assembly);
            builder.RegisterApiControllers(typeof(SalesPeopleController).Assembly);

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

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

            Container = container;

            // Web API
            var resolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
Exemple #6
0
        public static void RegisterContainer()
        {
            // Create the container builder.
            var builder = new ContainerBuilder();

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

            builder.Register(db =>
            {
                var dbName = ConfigurationManager.AppSettings["dbName"];
                return(new MongoClient().GetServer().GetDatabase(dbName));
            }).As <MongoDatabase>().InstancePerHttpRequest();

            builder.RegisterGeneric(typeof(Repository <>)).As(typeof(IRepository <>)).InstancePerHttpRequest();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .Where(t => t.Name.EndsWith("Service"))
            .AsSelf().InstancePerHttpRequest();

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

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

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

            // Configure MVC with the dependency resolver.
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemple #7
0
        public static IContainer RegisterDependencies()
        {
            var builder = new ContainerBuilder();

            var assembly = Assembly.GetExecutingAssembly();

            // Register your MVC controllers.
            builder.RegisterControllers(assembly);
            builder.RegisterApiControllers(assembly);

            RegisterContextsOn(builder);

            builder.RegisterModule <RepositoriesModule>();
            builder.RegisterModule <ServicesModule>();
            builder.RegisterModule <ValidatorsModule>();

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

            DependencyResolver.SetResolver(dependencyResolver);

            // Set Web API Dependency Resolver
            var webApiDependencyResolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = webApiDependencyResolver;

            ContainerAccessor.Container = () => dependencyResolver.RequestLifetimeScope;

            return(container);
        }
        public void WrapperResolvesAuthenticationFilterFromDependencyScope()
        {
            var builder = new ContainerBuilder();
            builder.Register<ILogger>(c => new Logger()).InstancePerDependency();
            var activationCount = 0;
            builder.Register<IAutofacAuthenticationFilter>(c => new TestAuthenticationFilter(c.Resolve<ILogger>()))
                .AsWebApiAuthenticationFilterFor<TestController>(c => c.Get())
                .InstancePerRequest()
                .OnActivated(e => activationCount++);
            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);
            var configuration = new HttpConfiguration { DependencyResolver = resolver };
            var requestMessage = new HttpRequestMessage();
            requestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, configuration);
            var contollerContext = new HttpControllerContext { Request = requestMessage };
            var controllerDescriptor = new HttpControllerDescriptor { ControllerType = typeof(TestController) };
            var methodInfo = typeof(TestController).GetMethod("Get");
            var actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo);
            var actionContext = new HttpActionContext(contollerContext, actionDescriptor);
            var context = new HttpAuthenticationContext(actionContext, Thread.CurrentPrincipal);
            var metadata = new FilterMetadata
            {
                ControllerType = typeof(TestController),
                FilterScope = FilterScope.Action,
                MethodInfo = methodInfo
            };
            var wrapper = new AuthenticationFilterWrapper(metadata);

            wrapper.OnAuthenticate(context);
            Assert.Equal(1, activationCount);
        }
Exemple #9
0
        /// <summary>
        /// http://docs.autofac.org/en/latest/integration/mvc.html
        /// </summary>
        protected IContainer RegisterContainer()
        {
            var builder = new ContainerBuilder();

            var thisAssembly = Assembly.GetExecutingAssembly();

            builder.RegisterControllers(thisAssembly);
            builder.RegisterApiControllers(thisAssembly);

            var mockData = bool.Parse(ConfigurationManager.AppSettings["UseMockData"]);

            builder.RegisterModule(new ApplicationModule(mockData));

            var container = builder.Build();

            // set mvc resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // set webapi resolver
            var resolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = resolver;

            return(container);
        }
Exemple #10
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new HttpConfiguration();

            configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            WebApiConfig.Register(configuration);
            //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            // Execute any other ASP.NET Web API-related initialization, i.e. IoC, authentication, logging, mapping, DB, etc.
            //ConfigureAuth(app);


            //IOC

            var builder = new ContainerBuilder();


            builder.RegisterApiControllers(Assembly.GetExecutingAssembly‌​());

            builder.RegisterInstance <ICalculatorService>(new CalculatorService());

            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);

            configuration.DependencyResolver = resolver;

            //

            app.UseWebApi(configuration);
        }
        /// <summary>
        ///     Registers the configuration
        /// </summary>
        public static IContainer Register(IAppBuilder app, HttpConfiguration configuration, IServiceFacade serviceFacade = null)
        {
            Condition.Requires(configuration, "configuration").IsNotNull();

            var builder = new ContainerBuilder();

            builder.RegisterModule(new ServiceModule(serviceFacade));

            // controllers
            builder.RegisterApiControllers(typeof(ControllerBase).Assembly);

            // request
            builder.RegisterHttpRequestMessage(configuration);

            // authorization
            builder.RegisterType <AuthorizationServerProvider>().As <IOAuthAuthorizationServerProvider>().SingleInstance();

            // set resolver
            var container = builder.Build();

            // set the dependency resolver for Web API
            var resolver = new AutofacWebApiDependencyResolver(container);

            configuration.DependencyResolver = resolver;
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(configuration);

            ConfigureOAuth(app, container);

            app.UseWebApi(configuration);

            return(container);
        }
Exemple #12
0
        private void OwinStartup(IAppBuilder app)
        {
            HttpConfiguration   config = new HttpConfiguration();
            IDependencyResolver resolver;

#if true
            Unity.IUnityContainer uc = new Unity.UnityContainer();

            uc.RegisterInstance(typeof(IPlop), new Plop());
            resolver = new UnityResolver(uc);
#else
            Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();

            builder.RegisterApiControllers(typeof(WorkerRole).Assembly);
            builder.RegisterInstance(new Plop()).As <IPlop>();
            Autofac.IContainer container = builder.Build();

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            resolver = new AutofacWebApiDependencyResolver(container);
#endif

            config.DependencyResolver = resolver;
            config.MapHttpAttributeRoutes();
            config.EnsureInitialized();

            app.UseWebApi(config);
        }
Exemple #13
0
        public void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

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

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


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

            var container = builder.Build();

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

            // Set the dependency resolver for MVC.
            var mvcResolver = new AutofacDependencyResolver(container);

            DependencyResolver.SetResolver(mvcResolver);

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

            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            ApplicationContainer.Container = container;
        }
        private static IContainer CreateContainer()
        {
            var builder  = new ContainerBuilder();
            var assembly = Assembly.GetExecutingAssembly();

            builder.RegisterType <SkillMatrixServiceLocator>().As <IServiceLocator>().SingleInstance();

            builder.RegisterType <DbFactory <SKMContext> >().As <IDbFactory <SKMContext> >().InstancePerLifetimeScope();
            builder.RegisterType <UnitOfWork <SKMContext> >().As <IUnitOfWork>().SingleInstance();

            builder.Register(c => HttpContext.Current.GetOwinContext().GetUserManager <AccountManager>())
            .As <AccountManager>();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).As <IAuthenticationManager>();

            builder.RegisterAssemblyTypes(typeof(SkillRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
            //// Services
            builder.RegisterAssemblyTypes(typeof(SkillService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            var container = builder.Build();
            var resolver  = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = resolver;

            SetMvcDependencyResolver(container);
            return(container);
        }
        public static IDependencyResolver SetAutofacContainer()
        {
            var builder = new ContainerBuilder();

            var currentAssembly = typeof(HomeController).Assembly;
            var apiAssembly     = typeof(CartController).Assembly;

            builder.RegisterControllers(currentAssembly);
            builder.RegisterApiControllers(apiAssembly);

            builder.RegisterType <GroceriesEntities>().InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(currentAssembly)
            .Where(t => t.Name.EndsWith("Initializer"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder.RegisterFilterProvider();

            IContainer container = builder.Build();

            var webApiResolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            return(new AutofacDependencyResolver(container));
        }
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);


            var container = new ContainerBuilder();

            container.RegisterControllers(AppDomain.CurrentDomain.GetAssemblies());
            container.RegisterApiControllers(AppDomain.CurrentDomain.GetAssemblies());

            container.RegisterType <StockTakeRepository>().As <IStockTakeRepository>();
            container.RegisterType <StockTakeService>().As <IStockTakeService>();

            var builder = container.Build();// RegisterServices.Register(builder);


            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder));

            var dependencyResolver = new AutofacWebApiDependencyResolver(builder);

            GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver;

            app.UseAutofacMiddleware(builder);

            app.UseAutofacMvc();


            using (var context = new ApplicationDbContext())
            {
                AccountDbInitializer.Seed(context);
            }
        }
Exemple #17
0
        private void ConfigureContainer(IAppBuilder app)
        {
            var assembly = this.GetType().Assembly;

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(assembly)
            .InstancePerLifetimeScope();

            var modules = AssemblyHelper.Scan <Module>(assembly);

            modules.ForEach(m => builder.RegisterModule(m));

            builder.RegisterAssemblyModules(assembly);

            extensionModules.Register(new RegisterContext(builder));

            var container = builder.Build();

            var dependencyResolver = new AutofacWebApiDependencyResolver(container);

            Config.DependencyResolver = dependencyResolver;

            // add lifetimescope to owin context.
            app.UseAutofacMiddleware(container);
            // add lifetimescope from owin to web api scope
            app.UseAutofacWebApi(Config);

            IoC.Initialize(container);

            app.UseWebApi(Config);

            logger.Info("Configure container completed.....");
        }
Exemple #18
0
        protected void Application_Start()
        {
            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
            // autofac container
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule <UserModule>();
            builder.RegisterModule <DataAccessModule>();

            // Auto Mapper v5 Support
            var mapperConfiguration = new MapperConfiguration(cfg =>
            {
                MappingConfiguration.Configure(typeof(UserModule).Assembly, cfg);
                MappingConfiguration.Configure(typeof(UsersBusinessProviderModule).Assembly, cfg);
            });

            var mapper = mapperConfiguration.CreateMapper();

            builder.RegisterInstance(mapper).As <IMapper>();

            var container = builder.Build();
            var resolver  = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = resolver;
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
        public async Task UriMaker_is_ctor_injected_using_Autofac()
        {
            var config = new HttpConfiguration();
            // Autofac
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // Web API routes
            var uriMakerContext = config.MapHttpAttributeRoutesAndUseUriMaker();

            builder.RegisterInstance(uriMakerContext).ExternallyOwned();
            builder.RegisterHttpRequestMessage(config);
            builder.RegisterGeneric(typeof(UriMaker <>)).AsSelf().InstancePerRequest();

            var container = builder.Build();
            var resolver  = new AutofacWebApiDependencyResolver(container);

            config.DependencyResolver = resolver;

            var client = new HttpClient(new HttpServer(config));
            var res    = await client.GetAsync("http://www.example.net/api/autofac/resources");

            Assert.Equal(HttpStatusCode.OK, res.StatusCode);
            var body = await res.Content.ReadAsAsync <ResourceState>();

            Assert.Equal("http://www.example.net/api/autofac/resources", body.self.ToString());
            Assert.Equal("http://www.example.net/api/autofac/resources?page=1&count=10", body.next.ToString());
            Assert.Equal("http://www.example.net/api/autofac/resources/0", body.first.ToString());
            Assert.Equal("http://www.example.net/api/autofac/resources/0?detailed=True", body.first_alternative.ToString());
        }
Exemple #20
0
        private static void GlobalConf(HttpConfiguration config, IAppBuilder app)
        {
            var container = GetServiceContainer(config, app);
            var resolver  = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
        public static HttpConfiguration ConfigureContainer(IAppBuilder app)
        {
            var configuration = GlobalConfiguration.Configuration;
            var builder       = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();
            builder.RegisterWebApiFilterProvider(configuration);

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .Where(x => x.Namespace.EndsWith(".Implementations"))
            .AsImplementedInterfaces();

            builder.RegisterGeneric(typeof(GenericRepository <>)).As(typeof(IGenericRepository <>)).InstancePerDependency();

            builder.RegisterType <AgileDbContext>().As <IAgileDbContext>().InstancePerRequest();
            LoadAndRegisterAssemblies(builder);

            var container = builder.Build();
            var resolver  = new AutofacWebApiDependencyResolver(container);

            configuration.DependencyResolver = resolver;
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(configuration);
            return(configuration);
        }
Exemple #22
0
        public async void WrapperResolvesActionFilterFromDependencyScope()
        {
            var builder = new ContainerBuilder();

            builder.Register <ILogger>(c => new Logger()).InstancePerDependency();
            var configuration = new HttpConfiguration();

            builder.RegisterWebApiFilterProvider(configuration);
            var activationCount = 0;

            builder.Register <IAutofacActionFilter>(c => new TestActionFilter(c.Resolve <ILogger>()))
            .AsWebApiActionFilterFor <TestController>(c => c.Get())
            .InstancePerRequest()
            .OnActivated(e => activationCount++)
            .GetMetadata(out var filterMetadata);

            var container = builder.Build();

            var resolver          = new AutofacWebApiDependencyResolver(container);
            var controllerContext = CreateControllerContext(resolver);
            var methodInfo        = typeof(TestController).GetMethod("Get");
            var actionDescriptor  = CreateActionDescriptor(methodInfo);
            var actionContext     = new HttpActionContext(controllerContext, actionDescriptor);

            var wrapper = new ContinuationActionFilterWrapper(filterMetadata.ToSingleFilterHashSet());

            await wrapper.ExecuteActionFilterAsync(actionContext, CancellationToken.None, () => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

            Assert.Equal(1, activationCount);
        }
Exemple #23
0
        public static void ConfigureContainer()
        {
            // получаем экземпляр контейнера
            var builder = new ContainerBuilder();

            // регистрируем контроллер в текущей сборке
            //MVC controller
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            //WebApi controller
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            // регистрируем споставление типов
            builder.RegisterType <EFUnitOfWork>().As <IUnitofWork>().
            WithParameter(new TypedParameter(typeof(AuctionContext),
                                             new AuctionContext("name=DefaultConnection")));
            builder.RegisterType <CustomerRoleProvider>();
            // создаем новый контейнер с теми зависимостями, которые определены выше
            var container = builder.Build();

            // установка сопоставителя зависимостей   MVC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            // установка сопоставителя зависимостей   WebApi
            var resolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
Exemple #24
0
        public static void ConfigureContainer()
        {
            // получаем экземпляр контейнера
            var builder = new ContainerBuilder();

            // регистрируем контроллер в текущей сборке
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterType <MeetingsRepository>().As <IMeetingsRepository>();
            builder.RegisterType <UserManagerRepository>().As <IUserManagerRepository>();
            builder.RegisterType <MeetingRoomRepository>().As <IMeetingRoomRepository>();
            builder.RegisterType <MoneyRepository>().As <IMoneyRepository>();

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

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

            System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            // Set the dependency resolver for MVC.
            var mvcResolver = new AutofacDependencyResolver(container);

            DependencyResolver.SetResolver(mvcResolver);

            // создаем новый контейнер с теми зависимостями, которые определены выше
            //container = builder.Build();

            // установка сопоставителя зависимостей
            //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemple #25
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));
        }
Exemple #26
0
        public static void CoreAutoFacInit()
        {
            var builder = new ContainerBuilder();

            // Add any Autofac modules or registrations.
            builder.RegisterModule(new AutofacModule());
            //var builder = new ContainerBuilder();
            //builder.RegisterType<ECERP_Base_UserRepository>().As<IECERP_Base_UserRepository>();

            //builder.AddSingleton<IECERP_Base_UserRepository, ECERP_Base_UserRepository>();
            //SetupResolveRules(builder);

            ////注册所有的Controllers
            //builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            //注册所有的ApiControllers
            //builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());


            ////注册api容器需要使用HttpConfiguration对象
            var container = builder.Build();
            var resolver  = new AutofacWebApiDependencyResolver(container);

            System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = resolver;

            ////注册api容器需要使用HttpConfiguration对象
            //HttpConfiguration config = GlobalConfiguration.Configuration;
            //config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            //  DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemple #27
0
        public static void Register(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();

            var myAssembly = Assembly.GetExecutingAssembly();

            // Register IoC for Repository
            builder.RegisterAssemblyTypes(myAssembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces();

            // Register IoC for Service
            builder.RegisterAssemblyTypes(myAssembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces();

            // Register IoC for Controller
            builder.RegisterApiControllers(myAssembly);

            // Config Autofac
            var container = builder.Build();

            var autofacResolver = new AutofacWebApiDependencyResolver(container);

            config.DependencyResolver = autofacResolver;
        }
Exemple #28
0
        public static void Register()
        {
            var builder = new ContainerBuilder();

            builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(RequestRepository <>)).As(typeof(IRequestRepository <>)).InstancePerLifetimeScope();
            builder.RegisterType <RequestUnitOfWork>().As <IRequestUnitOfWork>().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(Assembly.Load("SMS.SERVICES"))
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(Assembly.Load("SMS.FACADE"))
            .Where(t => t.Name.EndsWith("Facade"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
            var autoMapperProfile = new MapperConfigurationInternal();

            builder.Register(ctx => new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(autoMapperProfile);
            }));

            //register your mapper
            builder.Register(c => c.Resolve <MapperConfiguration>().CreateMapper(c.Resolve)).As <IMapper>().InstancePerLifetimeScope();
            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
Exemple #29
0
        public static void ConfigureAutofac()
        {
            var builder = new ContainerBuilder();
            var config  = GlobalConfiguration.Configuration;

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest().PropertiesAutowired();
            builder.RegisterWebApiFilterProvider(config);
            builder.RegisterAssemblyTypes(typeof(IBusiness).Assembly).AsImplementedInterfaces().InstancePerLifetimeScope().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

            #region Services
            builder.RegisterType <EmployeeService>().As <IEmployeeService>().InstancePerLifetimeScope().PropertiesAutowired();
            #endregion

            #region Helpers
            builder.RegisterType <JsonRequestHelper>().As <IJsonRequestHelper>().PropertiesAutowired();
            #endregion

            #region Factories
            builder.RegisterType <EmployeeFactory>().As <IEmployeeFactory>().InstancePerLifetimeScope().PropertiesAutowired();
            #endregion

            var container = builder.Build();
            var resolver  = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = resolver;
        }
        private static void SetAutofacWebAPIServices()
        {
            var configuration = GlobalConfiguration.Configuration;
            var builder       = new ContainerBuilder();

            // Configure the container with the integration implementations.
            builder.ConfigureWebApi(configuration);
            // Register API controllers using assembly scanning.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType <DefaultCommandBus>().As <ICommandBus>().InstancePerApiRequest();
            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerApiRequest();
            builder.RegisterType <DatabaseFactory>().As <IDatabaseFactory>().InstancePerApiRequest();
            builder.RegisterAssemblyTypes(typeof(CategoryRepository)
                                          .Assembly).Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerApiRequest();
            var services = Assembly.Load("EFMVC.Domain");

            builder.RegisterAssemblyTypes(services)
            .AsClosedTypesOf(typeof(ICommandHandler <>)).InstancePerApiRequest();
            builder.RegisterAssemblyTypes(services)
            .AsClosedTypesOf(typeof(IValidationHandler <>)).InstancePerApiRequest();
            var container = builder.Build();
            // Set the dependency resolver implementation.
            var resolver = new AutofacWebApiDependencyResolver(container);

            configuration.ServiceResolver.SetResolver(resolver);
        }
Exemple #31
0
        public async void WrapperResolvesActionFilterFromDependencyScope()
        {
            var builder = new ContainerBuilder();

            builder.Register <ILogger>(c => new Logger()).InstancePerDependency();
            var activationCount = 0;

            builder.Register <IAutofacActionFilter>(c => new TestActionFilter(c.Resolve <ILogger>()))
            .AsWebApiActionFilterFor <TestController>(c => c.Get())
            .InstancePerRequest()
            .OnActivated(e => activationCount++);
            var container = builder.Build();

            var resolver                  = new AutofacWebApiDependencyResolver(container);
            var controllerContext         = CreateControllerContext(resolver);
            var methodInfo                = typeof(TestController).GetMethod("Get");
            var actionDescriptor          = CreateActionDescriptor(methodInfo);
            var actionContext             = new HttpActionContext(controllerContext, actionDescriptor);
            var httpActionExecutedContext = new HttpActionExecutedContext(actionContext, null);
            var metadata                  = new FilterMetadata
            {
                ControllerType = typeof(TestController),
                FilterScope    = FilterScope.Action,
                MethodInfo     = methodInfo
            };
            var wrapper = new ActionFilterWrapper(metadata);

            await wrapper.OnActionExecutingAsync(actionContext, CancellationToken.None);

            Assert.Equal(1, activationCount);

            await wrapper.OnActionExecutedAsync(httpActionExecutedContext, CancellationToken.None);

            Assert.Equal(1, activationCount);
        }
Exemple #32
0
        /// <summary>
        /// Configuration method to configure startup of application
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration configuration = new HttpConfiguration();

            WebApiConfig.Register(configuration);

            //////////////////////////////AUTOFAC CONFIG/////////////////////START

            var builder = new ContainerBuilder();

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


            new ServicesRegistry().Register(builder);

            var container = builder.Build();
            // Create the depenedency resolver.
            var resolver = new AutofacWebApiDependencyResolver(container);

            configuration.DependencyResolver = resolver;
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(configuration);
            app.UseWebApi(configuration);
        }
        public void GetServicesReturnsEmptyEnumerableForUnregisteredService()
        {
            var container = new ContainerBuilder().Build();
            var resolver = new AutofacWebApiDependencyResolver(container);

            var services = resolver.GetServices(typeof(object));

            Assert.Equal(0, services.Count());
        }
        public void GetServiceReturnsNullForUnregisteredService()
        {
            var container = new ContainerBuilder().Build();
            var resolver = new AutofacWebApiDependencyResolver(container);

            var service = resolver.GetService(typeof(object));

            Assert.Null(service);
        }
        public void GetServicesReturnsRegisteredService()
        {
            var builder = new ContainerBuilder();
            builder.Register(c => new object());
            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);

            var services = resolver.GetServices(typeof(object));

            Assert.Equal(1, services.Count());
        }
        public void GetServiceReturnsRegisteredService()
        {
            var builder = new ContainerBuilder();
            builder.Register(c => new object());
            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);

            var service = resolver.GetService(typeof(object));

            Assert.NotNull(service);
        }
        public void AsModelBinderForTypesRegistersTypeModelBinder()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<Dependency>();
            builder.RegisterType<TestModelBinder>().AsModelBinderForTypes(typeof(TestModel1), typeof(TestModel2));
            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);
            var configuration = new HttpConfiguration { DependencyResolver = resolver };
            var provider = new AutofacWebApiModelBinderProvider();

            Assert.IsType<TestModelBinder>(provider.GetBinder(configuration, typeof(TestModel1)));
            Assert.IsType<TestModelBinder>(provider.GetBinder(configuration, typeof(TestModel2)));
        }
 public void AsModelBinderForTypesRegistersInstanceModelBinder()
 {
     var builder = new ContainerBuilder();
     var binder = new TestModelBinder(new Dependency());
     builder.RegisterInstance(binder).AsModelBinderForTypes(typeof(TestModel1));
     var container = builder.Build();
     var resolver = new AutofacWebApiDependencyResolver(container);
     var configuration = new HttpConfiguration { DependencyResolver = resolver };
     var provider = new AutofacWebApiModelBinderProvider();
     Assert.Same(binder, provider.GetBinder(configuration, typeof(TestModel1)));
 }
        public void BeginScopeReturnsNewScopeOnEachCall()
        {
            var builder = new ContainerBuilder();
            builder.Register(c => new object());
            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);

            Assert.NotSame(resolver.BeginScope(), resolver.BeginScope());
        }