当前位置: 首页>>代码示例>>C#>>正文


C# IAppBuilder.UseAutofacMiddleware方法代码示例

本文整理汇总了C#中IAppBuilder.UseAutofacMiddleware方法的典型用法代码示例。如果您正苦于以下问题:C# IAppBuilder.UseAutofacMiddleware方法的具体用法?C# IAppBuilder.UseAutofacMiddleware怎么用?C# IAppBuilder.UseAutofacMiddleware使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IAppBuilder的用法示例。


在下文中一共展示了IAppBuilder.UseAutofacMiddleware方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Configuration

        public void Configuration(IAppBuilder app)
        {
            // Setup db context for use in DI
            app.Use(async (context, next) =>
            {
                TestDbContext dbContext = _dbContextFactory(context);
                context.Set(DbContextKey, dbContext);

                await next();

                dbContext.Dispose();
            });

            var appContainerBuilder = new ContainerBuilder();
            appContainerBuilder.Register(ctx => HttpContext.Current.GetOwinContext()).As<IOwinContext>();
            appContainerBuilder.Register(c => c.Resolve<IOwinContext>().Get<TestDbContext>(DbContextKey)).As<TestDbContext>();
            appContainerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            var appContainer = appContainerBuilder.Build();
            app.UseAutofacMiddleware(appContainer);

            var httpConfig = GetWebApiConfiguration();
            httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(appContainer);
            app.UseWebApi(httpConfig);
            app.UseAutofacWebApi(httpConfig);
        }
开发者ID:Eclarian,项目名称:JSONAPI.NET,代码行数:25,代码来源:Startup.cs

示例2: ConfigureAutofac

        public void ConfigureAutofac(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<ConfigurationProvider>()
                .As<IConfigurationProvider>();

            builder.RegisterType<TelemetryService>()
                .As<ITelemetryService>();

            builder.RegisterType<IotHubRepository>()
               .As<IIotHubRepository>();

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

            var container = builder.Build();

            //Setup Autofac dependency resolver for MVC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            //Setup Autofac dependency resolver for WebAPI
            HttpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

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


        }
开发者ID:b3540,项目名称:azure-iot-predictive-maintenance,代码行数:29,代码来源:Startup.Autofac.cs

示例3: Configuration

        public void Configuration(IAppBuilder app)
        {
            var configuration = new ConfigurationService();

            var builder = new ContainerBuilder();
            builder.Register(c => configuration).As<ConfigurationService>().SingleInstance();
            builder.Register(c => configuration.CurrentConfiguration).As<IAppConfiguration>().SingleInstance();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();

            var container = AutofacBootstrapper.Initialize(builder);

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Must register Autofac middleware FIRST!
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app, configuration.CurrentConfiguration);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = JwtClaimTypes.Subject;
            AntiForgeryConfig.RequireSsl = true;
            AntiForgeryConfig.CookieName = Prsd.Core.Web.Constants.CookiePrefix + Constants.AntiForgeryCookieName;

            MvcHandler.DisableMvcResponseHeader = true;

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ModelBinders.Binders.DefaultBinder = new TrimModelBinder();
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(WeeeRequiredAttributeAdapter));

            ApplicationVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
开发者ID:EnvironmentAgency,项目名称:prsd-weee,代码行数:34,代码来源:Startup.cs

示例4: ConfigureAutofac

        public void ConfigureAutofac(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // register the class that sets up bindings between interfaces and implementation
            builder.RegisterModule(new WebAutofacModule());

            // register configuration provider
            builder.RegisterType<ConfigurationProvider>().As<IConfigurationProvider>();

            // register Autofac w/ the MVC application
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // Register the WebAPI controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var container = builder.Build();

            // Setup Autofac dependency resolver for MVC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Setup Autofac dependency resolver for WebAPI
            Startup.HttpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            // 1.  Register the Autofac middleware 
            // 2.  Register Autofac Web API middleware,
            // 3.  Register the standard Web API middleware (this call is made in the Startup.WebApi.cs)
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(Startup.HttpConfiguration);
        }
开发者ID:smartpcr,项目名称:azure-iot-remote-monitoring,代码行数:30,代码来源:Startup.Autofac.cs

示例5: Configuration

        public void Configuration(IAppBuilder app)
        {
            // Loads the config from our App.config
            XmlConfigurator.Configure();

            // MassTransit to use Log4Net
            Log4NetLogger.Use();

            var container = IocConfig.RegisterDependencies();

            // Sets the Mvc resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Sets Mvc Owin resolver as well
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            // Starts Mass Transit Service bus, and registers stopping of bus on app dispose
            var bus = container.Resolve<IBusControl>();
            var busHandle = bus.StartAsync().Result;

            if (app.Properties.ContainsKey("host.OnAppDisposing"))
            {
                var context = new OwinContext(app.Properties);
                var token = context.Get<CancellationToken>("host.OnAppDisposing");
                if (token != CancellationToken.None)
                {
                    token.Register(() => busHandle.Stop(TimeSpan.FromSeconds(30)));
                }
            }
        }
开发者ID:maldworth,项目名称:tutorial-masstransit-send-vs-publish,代码行数:31,代码来源:Startup.cs

示例6: Configuration

        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            ConfigureFilters(app, config);
            ConfigureWebApi(app, config);

            var container = ConfigureDI(app, config);

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

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {
                Provider = container.Resolve<IOAuthBearerAuthenticationProvider>()
            });

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/auth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
                Provider = container.Resolve<IOAuthAuthorizationServerProvider>()
            });

            app.UseWebApi(config);
        }
开发者ID:o-panikarovskiy,项目名称:fms,代码行数:26,代码来源:Startup.cs

示例7: Configuration

        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // REGISTER DEPENDENCIES
            builder.RegisterType<OnlineLibDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<LibRoleStore>().As<IRoleStore<LibRole, Guid>>().InstancePerRequest();
            builder.RegisterType<LibUserStore>().As<IUserStore<LibUser, Guid>>().InstancePerRequest();
            builder.RegisterType<LibUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<LinRoleManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<LibSignInManager>().AsSelf().InstancePerRequest();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();
            builder.RegisterType<LibraryRepository>().As<ILibraryRepository>().InstancePerRequest();
            builder.RegisterType<BooksRepository>().As<IBooksRepository>().InstancePerRequest();
            builder.RegisterType<EmailService>().As<IIdentityMessageService>().InstancePerRequest();

            // REGISTER CONTROLLERS
               // builder.RegisterControllers<AccountController>(typeof (ILibraryRepository)).AsSelf().InstancePerRequest();
            builder.RegisterControllers(typeof (MvcApplication).Assembly);

            // BUILD CONTAINER
            var container = builder.Build();

            // SET AUTOFAC DEPENDENCY RESOLVER
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // REGISTER AUTOFAC WITH OWIN
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
        }
开发者ID:krypton9208,项目名称:OnlineLib,代码行数:33,代码来源:Startup.cs

示例8: ConfigureDI

        public void ConfigureDI(IAppBuilder app, HttpConfiguration config)
        {
            // Start to build a container that will be able to produce objects
            var builder = new ContainerBuilder();

            // Register all the WebApi controllers in the Api assmebly, so that the container knows about them and can fill their dependencies when a controller is created.
            builder.RegisterApiControllers(typeof(Startup).Assembly);

             //Register the objects/types you want to be accessible from the container
            builder.Register(c => new UserDbContext()).As<UserDbContext>().InstancePerRequest();
            builder.Register(c =>
            {
                return new ApplicationUserManager(
                    new UserStore<ApplicationUser>(c.Resolve<UserDbContext>())
                );
            }).As<IApplicationUserManager>();

            // generate a container
            var container = builder.Build();

            // add a resolver to the WebApi framework so that it knows when it creates a controller it should ask the container for the controller.
            // before trying to create one with an empty constructor instead
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            // Add container into the WebApi pipeline
            // Note: Not used in this project, but useful for creating custom Middleware and having their dependencies filled in.
            // See http://alexmg.com/owin-support-for-the-web-api-2-and-mvc-5-integrations-in-autofac/ for more information
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
        }
开发者ID:Ragabon,项目名称:GadaInternational-Users,代码行数:30,代码来源:Startup.DI.cs

示例9: Configuration

        public void Configuration(IAppBuilder app)
        {
            TI.trace("StartupServerAutofac", "Begin in memory server setup");
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var configuration = new HttpConfiguration();
            //configuration.EnableSystemDiagnosticsTracing();
            //configuration.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //); 
            //add some temp route hacks
            configuration.Routes.MapHttpRoute(
                name: "Login1",
                routeTemplate: "Login/Login",
                defaults: new { controller = "Login", action = "LoginGet" });
             
            WebApiConfig.RegisterRoutes(configuration);
            WebApiConfig.RegisterIntegrationRoutes(configuration);
            DB_TestingHelper dbHelper = DefaultDbTestingHelper.GetDefaultDbTestingHelper();
            ContainerBuilder b = IOCHelper.InitializeServerWithAutofacContainer(dbHelper.Server_DistributrExmxConnection, dbHelper.MongoConnectionString, "win", dbHelper.MongoAuditingConnectionString);
            Assembly a = Assembly.GetAssembly(typeof(Distributr.WebApi.ApiControllers.CommandController));
            b.RegisterApiControllers(a);
            Autofac.IContainer c = b.Build();
            System.Web.Http.Dependencies.IDependencyResolver r = new AutofacWebApiDependencyResolver(c) ;
            configuration.DependencyResolver = r;
            app.UseAutofacMiddleware(c);
            app.UseAutofacWebApi(configuration);
            app.UseWebApi(configuration);
            sw.Stop();
            TI.trace("[StartupServerAutofac]",
                string.Format("Time taken to setup in memory server {0}", sw.ElapsedMilliseconds));

        }
开发者ID:asanyaga,项目名称:BuildTest,代码行数:35,代码来源:StartupServerAutofac.cs

示例10: Configuration

        public void Configuration(IAppBuilder app)
        {
            var configuration = new JsonApiConfiguration();
            configuration.RegisterEntityFrameworkResourceType<Building>();
            configuration.RegisterEntityFrameworkResourceType<City>();
            configuration.RegisterEntityFrameworkResourceType<Comment>();
            configuration.RegisterEntityFrameworkResourceType<Company>();
            configuration.RegisterEntityFrameworkResourceType<Language>();
            configuration.RegisterEntityFrameworkResourceType<LanguageUserLink>(c =>
            {
                c.OverrideDefaultFilterById(LanguageUserLinkFilterByIdFactory);
                c.OverrideDefaultSortById(LanguageUserLinkSortByIdFactory);
            });
            configuration.RegisterResourceType<Post>();
            configuration.RegisterEntityFrameworkResourceType<State>();
            configuration.RegisterEntityFrameworkResourceType<Tag>();
            configuration.RegisterEntityFrameworkResourceType<User>();
            configuration.RegisterEntityFrameworkResourceType<UserGroup>();
            configuration.RegisterResourceType<Sample>(); // Example of a resource type not controlled by EF
            configuration.RegisterMappedType<Starship, StarshipDto, StarshipDocumentMaterializer>(c =>
            {
                c.ConfigureRelationship(s => s.Officers,
                    rc => rc.UseMaterializer<StarshipOfficersRelatedResourceMaterializer>());
                c.ConfigureRelationship(s => s.ShipCounselor,
                    rc => rc.UseMaterializer<StarshipShipCounselorRelatedResourceMaterializer>());
            }); // Example of a resource that is mapped from a DB entity
            configuration.RegisterResourceType<StarshipOfficerDto>();

            var configurator = new JsonApiHttpAutofacConfigurator();
            configurator.OnApplicationLifetimeScopeCreating(builder =>
            {
                builder.Register(c => _dbContextFactory())
                    .AsSelf()
                    .As<DbContext>()
                    .InstancePerRequest();
                builder.RegisterModule<JsonApiAutofacEntityFrameworkModule>();
                builder.RegisterType<CustomEntityFrameworkResourceObjectMaterializer>()
                    .As<IEntityFrameworkResourceObjectMaterializer>();
                builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            });
            configurator.OnApplicationLifetimeScopeBegun(applicationLifetimeScope =>
            {
                // TODO: is this a candidate for spinning into a JSONAPI.Autofac.WebApi.Owin package? Yuck
                app.UseAutofacMiddleware(applicationLifetimeScope);
            });

            var httpConfig = new HttpConfiguration
            {
                IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
            };

            // Additional Web API routes
            httpConfig.Routes.MapHttpRoute("Samples", "samples", new { Controller = "Samples" });
            httpConfig.Routes.MapHttpRoute("Search", "search", new { Controller = "Search" });
            httpConfig.Routes.MapHttpRoute("Trees", "trees", new { Controller = "Trees" });

            configurator.Apply(httpConfig, configuration);
            app.UseWebApi(httpConfig);
            app.UseAutofacWebApi(httpConfig);
        }
开发者ID:BradBarnich,项目名称:JSONAPI.NET,代码行数:60,代码来源:Startup.cs

示例11: Configure

        public static void Configure(IAppBuilder app)
        {
            //Autofac configuration
            var builder = new ContainerBuilder();
            // Get your HttpConfiguration.
            var config = new HttpConfiguration();

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<AccountController>().InstancePerRequest();
            builder.RegisterType<PhoneBookContext>().InstancePerRequest();

            //dependenses resolving
            builder.RegisterType<MainUserManager>().As<IMainUserManager>().InstancePerRequest();
            builder.Register(c => new UserStore<User>(c.Resolve<PhoneBookContext>())).AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterType<ApplicationUserManager>().AsSelf();

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            app.UseAutofacWebApi(config);
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);
        }
开发者ID:ramzzzay,项目名称:PhoneBook,代码行数:27,代码来源:AutofacConfig.cs

示例12: ConfigureMobileApp

        /// <summary>
        /// Configures the webApi dependency injection to start the service.
        /// </summary>
        /// <param name="app">The Azure app service mobile app to configure.</param>
        public static void ConfigureMobileApp(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Services.Add(typeof(IExceptionLogger), new ApplicationInsightsExceptionLogger());

            IContainer container = ConfigureWebApiDependencies();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.MapHttpAttributeRoutes();

            new MobileAppConfiguration()
                .AddMobileAppHomeController()
                .MapApiControllers()
                .ApplyTo(config);

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

            // Configure Application Insights Telemetry.
            TelemetryConfiguration.Active.InstrumentationKey = SystemContext.Current.Environment.InstrumentationKey;

            var rootPath = HttpContext.Current.Server.MapPath("~");
            var serverPath = Path.Combine(rootPath, "bin");

            using (var scope = container.BeginLifetimeScope())
            {
                var repository = scope.Resolve<IRepository>();

                // Do database initialization synchronously
                repository.InitializeDatabaseIfNotExisting(serverPath).ConfigureAwait(false).GetAwaiter().GetResult();
            }
        }
开发者ID:Microsoft,项目名称:Appsample-Photosharing,代码行数:36,代码来源:Startup.MobileApp.cs

示例13: Configuration

        public void Configuration(IAppBuilder app)
        {
            var listener = (HttpListener) app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemeSelectorDelegate = r =>
            {
                Log.InfoFormat("Request from {0}", r.RemoteEndPoint);

                if (r.RemoteEndPoint != null && (_appSettings.IpAccessList.Contains(r.RemoteEndPoint.Address.ToString())))
                {
                    Log.InfoFormat("Ip listed, applying {0} authentication scheme", AuthenticationSchemes.Anonymous);
                    return AuthenticationSchemes.Anonymous;
                }

                Log.InfoFormat("Ip unknown, applying {0} authentication scheme", AuthenticationSchemes.IntegratedWindowsAuthentication);
                return AuthenticationSchemes.IntegratedWindowsAuthentication;
            };

            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();
            builder.RegisterInstance(new DeployOption(_appSettings.InstallPath)).As<IDeployOption>();

            ;            var container = builder.Build();

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            var resolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = resolver;

            app.UseAutofacMiddleware(container);
            app.UseWebApi(config);
        }
开发者ID:kaanjin,项目名称:Monopus,代码行数:33,代码来源:WebApiStartup.cs

示例14: Configuration

        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();


            app.UseAutofacMiddleware(container);

            var config = new HttpConfiguration();
            //config.EnableSwagger(c => c.SingleApiVersion("v1", "Feature Toggle Service API"))
            //      .EnableSwaggerUi();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.MapHttpAttributeRoutes();

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

            StartFeatureToggleService(container);

            //app.UseWebApi(config);
        }
开发者ID:momo3038,项目名称:FeatureToggleService,代码行数:26,代码来源:Startup.cs

示例15: Start

        protected virtual void Start(IAppBuilder app, IContainer container)
        {
            var config = CreateHttpConfiguration();

            ConfigureWebApi(config);

            if (Settings.ShowExceptionDetails)
            {
                app.UseErrorPage(new ErrorPageOptions
                {
                    ShowExceptionDetails = true,
                    ShowSourceCode = true
                });
            }
            
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);
            RegisterSignalR(container, app);

            app.UseStageMarker(PipelineStage.MapHandler);

            RegisterServices(container, app, config);
            
            RegisterShutdown(app, container);

            StartIndexingIfConfigured(container);
        }
开发者ID:jjchiw,项目名称:NuGet.Lucene,代码行数:28,代码来源:Startup.cs


注:本文中的IAppBuilder.UseAutofacMiddleware方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。