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


C# WebApi.AutofacWebApiDependencyResolver类代码示例

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


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


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