• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# WebApi.AutofacWebApiDependencyResolver类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Autofac.Integration.WebApi.AutofacWebApiDependencyResolver的典型用法代码示例。如果您正苦于以下问题:C# AutofacWebApiDependencyResolver类的具体用法?C# AutofacWebApiDependencyResolver怎么用?C# AutofacWebApiDependencyResolver使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



AutofacWebApiDependencyResolver类属于Autofac.Integration.WebApi命名空间,在下文中一共展示了AutofacWebApiDependencyResolver类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: UriMaker_is_ctor_injected_using_Autofac

        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());

        }
开发者ID:modulexcite,项目名称:drum,代码行数:27,代码来源:InjectionUsingAutofacTests.cs


示例2: RegisterContainer

        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));
        }
开发者ID:Myslik,项目名称:opencat,代码行数:32,代码来源:ContainerConfig.cs


示例3: Application_Start

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

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

            Database.SetInitializer<MusicstoreContext>(null);
            Database.SetInitializer(new CreateDatabaseIfNotExists<MusicstoreContext>());
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<MusicstoreContext,
                Data.Migrations.Configuration>());

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            var builder = new ContainerBuilder();

            #region data layer
            //var dataSettingsManager = new DataSettingsManager();
            //var dataProviderSettings = dataSettingsManager.LoadSettings();
            #endregion

            var db = new MusicstoreContext();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //builder.RegisterGeneric(typeof(EfRepository<>)).AsImplementedInterfaces();
            builder.Register<IRepository>(c => new EfRepository(db)).InstancePerApiRequest();
            //builder.Register<IRepository<Artist>>(c => new EfRepository<Artist>(new MusicstoreContext())).InstancePerApiRequest();
            //builder.Register<IRepository<Song>>(c => new EfRepository<Song>(new MusicstoreContext())).InstancePerApiRequest();

            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
开发者ID:rosteslav,项目名称:TelerikAkademy,代码行数:35,代码来源:Global.asax.cs


示例4: RegisterResolver

        public static void RegisterResolver()
        {
            var resolver = new AutofacWebApiDependencyResolver(RegisterServices(new ContainerBuilder()));

            // Configure Web API with the dependency resolver.
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
开发者ID:anushan78,项目名称:GitRepos,代码行数:7,代码来源:AutofacWebApi.cs


示例5: Register

        public static void Register(HttpConfiguration config)
        {
            // Create the container builder.
            var builder = new ContainerBuilder();

            // Register MVC 4 Contrrollers
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

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

            //register Domain Depedencies
            builder.RegisterModule(new Domain.AutofacModule());

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

            // SET Web API resolver
            // Create the depenedency resolver.
            var resolver = new AutofacWebApiDependencyResolver(container);
            // Configure Web API with the dependency resolver.
            config.DependencyResolver = resolver;

            //set MVC4 resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
开发者ID:kkurni,项目名称:KK-DemoMVC,代码行数:26,代码来源:AutofacConfig.cs


示例6: Setup

        public static void Setup()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            // Register for API Controllers
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterFilterProvider();
            builder.RegisterModelBinderProvider();
            builder.RegisterModule<AutofacWebTypesModule>();

            // Find all autofac modules and include them.
            builder.RegisterModule<IdentityModule>();

            // Find all IStartable tasks and register them.
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            builder.RegisterAssemblyTypes(assemblies)
                .AssignableTo<IStartable>()
                .As<IStartable>()
                .SingleInstance();

            // Enable property injection into action filters (including authorize attribute).
            builder.RegisterFilterProvider();

            IContainer container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
开发者ID:vietplayfuri,项目名称:Asp_Master,代码行数:29,代码来源:DependancyInjectionConfig.cs


示例7: DependencyInjectionConfiguration

        protected void DependencyInjectionConfiguration()
        {
            //Get all references assemblies
            var coreAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            var preferenceAssemblies = coreAssemblies.SelectMany(ca => ca.GetReferencedAssemblies());

            // Load assemblies
            var assemblies = coreAssemblies.Select(ca => ca.GetName())
                .Union(preferenceAssemblies)
                .Distinct()
                .Select((Assembly.Load))
                .ToArray();

            var builder = new ContainerBuilder();
            DependencyRegistrar.Register(builder, assemblies);

            var container = builder.Build();

            DependencyRegistrar.GlobalContainer = container;

            // Register for MVC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Register for ASP.NET Web API
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
开发者ID:tranphuong02,项目名称:giat-ghe,代码行数:27,代码来源:Global.asax.cs


示例8: Register

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

            config.EnableQuerySupport();
            config.EnableSystemDiagnosticsTracing();

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

            var builder = new ContainerBuilder();

            builder.RegisterType<ToDoItemMap>().As<IMap<ToDoItem, ToDoItemDto>>();

            var webApiAssembly = Assembly.Load("WebApi");
            builder.RegisterApiControllers(webApiAssembly);

            var dataAssembly = Assembly.Load("Data");
            builder.RegisterAssemblyTypes(dataAssembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces()
                .InstancePerApiRequest();

            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = resolver;
        }
开发者ID:knandiwal,项目名称:Simple-ToDo,代码行数:31,代码来源:WebApiConfig.cs


示例9: Application_Start

        protected void Application_Start()
        {
            EngineContext.Initialize(false);

            var configuration = GlobalConfiguration.Configuration;


            var resolver = new AutofacWebApiDependencyResolver(
                EngineContext.Current.ContainerManager.Container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;

            //注册AutoMapper
            //TODO:这里可能产生耦合,考虑是否使用接口
            var mapperConfig = new AutoMapperRegistrar();
            mapperConfig.Register();
            

            //GlobalConfiguration.Configuration.DependencyResolver
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
           

            //TODO 阻止循环引用序列化(记录到RRDL)
            //阻止循环引用序列化
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            //json.SerializerSettings.PreserveReferencesHandling =
            //    Newtonsoft.Json.PreserveReferencesHandling.Objects;
            json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        }
开发者ID:hiyouth,项目名称:R2.DisasterWebAPI,代码行数:31,代码来源:Global.asax.cs


示例10: Application_Start

        protected void Application_Start()
        {
            Error += (sender, args) => Debug.Write(args);

            (new FeatureBeeContext()).Initialize(true);

            var container = new DIConfiguration().BuildApplicationContainer();

            // Configure MVC with the dependency resolver.
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Configure SignalR with the dependency resolver.
            GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);

            // Configure Web API with the dependency resolver.
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;

            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
开发者ID:cw2018,项目名称:FeatureBee,代码行数:25,代码来源:Global.asax.cs


示例11: Application_Start

        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();
        }
开发者ID:GarthOrmsby,项目名称:AgileR,代码行数:32,代码来源:Global.asax.cs


示例12: RegisterContainer

        public static IContainer RegisterContainer(HttpConfiguration config) {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            //Settings
            builder.RegisterType<WebConfigApplicationSettings>().As<IApplicationSettings>().InstancePerRequest();
            //Logger
            builder.RegisterType<Log4NetAdapter>().As<ILogger>().InstancePerRequest();
            //EF
            builder.RegisterType<ApplicationDbContext>().As<IApplicationDbContext>().InstancePerRequest();
            builder.RegisterType<IdentityDbContext<ApplicationUser>>();
            //Usermanager
            //builder.RegisterInstance(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())));
            //Services
            builder.RegisterType<CurrentUserService>().As<ICurrentUserService>().InstancePerRequest();
            builder.RegisterType<AccountService>().As<IAccountService>().InstancePerRequest();
            builder.RegisterType<TripService>().As<ITripService>().InstancePerRequest();
            builder.RegisterType<AddressService>().As<IAddressService>().InstancePerRequest();
            builder.RegisterType<CarService>().As<ICarService>().InstancePerRequest();
            builder.RegisterType<GoogleDistanceCalculatorService>().As<IDistanceCalculatorService>().InstancePerRequest();

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

            config.DependencyResolver = resolver;

            return container;
        }
开发者ID:nvdvlies,项目名称:MileageTracker.AspNetWebApi,代码行数:28,代码来源:AutofacConfig.cs


示例13: RegisterIoc

        public static void RegisterIoc()
        {
            var builder = new ContainerBuilder();

            // registrar autofac para resolver las dependencías de los controladores
              builder.RegisterControllers(typeof(Tarea.Web.Controllers.TareaController).Assembly);
            // registrar para IDatabase - 1 Instancia por request
            builder.Register(c => new Database("Default"))
                .As<IDatabase>()
                .SingleInstance();
            // registar el servicio

            builder.RegisterType<TareaServicio2>().
                As<ITareaServicio>().
                InstancePerRequest();

            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerRequest();
            builder.RegisterType<Uow>().As<IUnitOfWork>().InstancePerRequest();

            // registar para los filters (aun no tenemos)
            builder.RegisterFilterProvider();

            builder.RegisterApiControllers(typeof(Tarea.Web.Controllers.TareaDataController).Assembly);
            // completar la config de autofac
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
开发者ID:cbdavid14,项目名称:kpensar-tarea-di,代码行数:30,代码来源:AutofacConfig.cs


示例14: InitializeIoC

        private static void InitializeIoC(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();
            //builder.ConfigureWebApi(GlobalConfiguration.Configuration);

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterType<EventoRepository>().As<Eventos>();
            builder.RegisterType<GrupoRepository>().As<Grupos>();
            builder.RegisterType<LocalRepository>().As<Locais>();
            builder.RegisterType<UsuarioRepository>().As<Usuarios>();
            builder.RegisterType<UsuarioTokenRepository>().As<UsuarioTokens>();

            builder.RegisterType<RemoveConflitoService>().As<DomainEventHandler<EventoCanceladoEvent>>();
            builder.RegisterType<RemoveConflitoService>().As<DomainEventHandler<ReservaDeLocalAlteradaEvent>>();
            builder.RegisterType<RemoveConflitoService>().As<DomainEventHandler<HorarioDeEventoAlteradoEvent>>();

            builder.Register<AgendaEventoService>(c => new AgendaEventoService(c.Resolve<Eventos>()));
            builder.Register<TrocaSenhaService>(c => new TrocaSenhaService(c.Resolve<Usuarios>(), c.Resolve<UsuarioTokens>()));

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

            IoCWorker.Initialize(resolver);
        }
开发者ID:danielsilva,项目名称:--Integer--,代码行数:26,代码来源:WebApiConfig.cs


示例15: SetAutofacWebAPIServices

        private static void SetAutofacWebAPIServices()
        {
            var configuration = GlobalConfiguration.Configuration;
            var builder = new ContainerBuilder();

            // Configure the container with the integration implementations.
            builder.ConfigureWebApi(configuration);

            builder.RegisterType<DigitalAccountsUnitOfWork>()
                         .As<IDigitalAccountsUnitOfWork>()
                         .InstancePerLifetimeScope();

            builder.RegisterType<DigitalAccountsService>()
                         .As<IDigitalAccountsService>()
                         .InstancePerLifetimeScope();

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

            // Register API controllers using assembly scanning.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var container = builder.Build();
            // Set the dependency resolver implementation.
            var resolver = new AutofacWebApiDependencyResolver(container);

            configuration.ServiceResolver.SetResolver(resolver);

            AutofacServiceHostFactory.Container = container;
        }
开发者ID:ivpadim,项目名称:architecture,代码行数:32,代码来源:Bootstrapper.cs


示例16: 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


示例17: Config

        public static void Config()
        {
            var builder = new ContainerBuilder();

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

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

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

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

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

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

            builder.RegisterModule(new ManagerModule());

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

            var mvcResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(mvcResolver);
        }
开发者ID:pasha369,项目名称:RestaurantManagementSystem,代码行数:33,代码来源:AutofacConfig.cs


示例18: Register

        /// <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;
        }
开发者ID:RMcD,项目名称:AngularSkeleton.NET,代码行数:35,代码来源:ContainerConfig.cs


示例19: WrapperResolvesAuthenticationFilterFromDependencyScope

        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.That(activationCount, Is.EqualTo(1));
        }
开发者ID:RoymanJing,项目名称:Autofac,代码行数:32,代码来源:AuthenticationFilterWrapperFixture.cs


示例20: Verify_Routing_Rules

        public void Verify_Routing_Rules()
        {
            // Initialize AutoFac WebApi stuff 
            IoC.BuildContainer();
            var config = new HttpConfiguration();
            var webApiDependencyResolver = new AutofacWebApiDependencyResolver(IoC.Container);
            config.DependencyResolver = webApiDependencyResolver;
            WebApiConfig.RegisterRoutes(config.Routes);
            

            // arrange/act/assert
            var route = RouteInfo.Verify(config, HttpMethod.Get, BaseUri + "1", typeof(ProductsController), "Default");
            route.VerifyRouteData("id", "1");

            // arrange/act/assert
            route = RouteInfo.Verify(config, HttpMethod.Get, BaseUri, typeof(ProductsController), "Default");

            // arrange/act/assert
            route = RouteInfo.Verify(config, HttpMethod.Get, BaseUri + "details", typeof(ProductsController), "Details");
            
            // arrange/act/assert
            route = RouteInfo.Verify(config, HttpMethod.Get, BaseUri + "?$filter=startswith(Name, 'Mountain') eq true&$top=2&$skip=3", typeof(ProductsController), "Default");
            
            // arrange/act/assert
            route = RouteInfo.Verify(config, HttpMethod.Post, BaseUri, typeof(ProductsController), "Default");

            // arrange/act/assert
            route = RouteInfo.Verify(config, HttpMethod.Put, BaseUri + "1", typeof(ProductsController), "Default");

            // arrange/act/assert
            route = RouteInfo.Verify(config, HttpMethod.Put, BaseUri + "1/mark-sold-out", typeof(ProductsController), "MarkSoldOut");

            // arrange/act/assert
            route = RouteInfo.Verify(config, HttpMethod.Delete, BaseUri + "1", typeof(ProductsController), "Default");
        }
开发者ID:benpriebe,项目名称:ServerRI,代码行数:35,代码来源:ProductsControllerTest.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# AutomationTool.CommandEnvironment类代码示例发布时间:2022-05-24
下一篇:
C# Autofac.ContainerBuilder类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap