public IServiceProvider ConfigureServices(IServiceCollection services) { var bootstrapper = new MyBootstrapper(); var builder = new ContainerBuilder(); builder.Populate(bootstrapper); builder.Populate(services); Container = builder.Build(); return Container.Resolve<IServiceProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); // Create the Autofac container builder. var builder = new ContainerBuilder(); // Add any Autofac modules or registrations. builder.RegisterModule(new ServiceModule()); // Populate the services. builder.Populate(services); // Build the container. var container = builder.Build(); // Resolve and return the service provider. return container.Resolve<IServiceProvider>(); }
/// <summary> /// Sets up the DI container. Loads types dynamically (http://docs.autofac.org/en/latest/register/scanning.html) /// </summary> public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); /* TODO: #10 services.AddCaching(); services.AddSession(); services.ConfigureSession(o => { o.IdleTimeout = TimeSpan.FromMinutes(5); });*/ services.AddTransient<WopiAuthorizationAttribute>(); // Autofac resolution var builder = new ContainerBuilder(); // Configuration Configuration configuration = new Configuration(); configuration.AddEnvironmentVariables(); builder.RegisterInstance(configuration).As<IConfiguration>().SingleInstance(); // File provider implementation var providerAssembly = configuration.Get("WopiFileProviderAssemblyName"); var assembly = AppDomain.CurrentDomain.Load(new AssemblyName(providerAssembly)); builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces(); builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); }
// This method gets called by a runtime. // Use this method to add services to the container public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); var builder = new ContainerBuilder(); builder.RegisterType<ConcreteCacheProvider>().As<ICacheProvider>(); builder.RegisterType<SerilogLoggerFactory>().As<ILoggerFactory>(); builder.RegisterType(typeof(ThingyRepository)).Named<IRepository<Thingy>>("repository"); builder.RegisterGenericDecorator( typeof(CachedRepository<>), typeof(IRepository<>), fromKey: "repository") .Keyed("decorated", typeof(IRepository<>)); builder.RegisterGenericDecorator( typeof(PerformanceLoggingRepository<>), typeof(IRepository<>), fromKey: "decorated"); builder.Populate(services); var container = builder.Build(); return container.ResolveOptional<IServiceProvider>(); }
public static ILifetimeScope CreateAutofacContainer(this IServiceCollection services, IConfigurationRoot configuration) { var builder = new ContainerBuilder(); // Load web specific dependencies builder.RegisterType<AuthMessageSender>() .As<IEmailSender>().InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(typeof(Startup).GetTypeInfo().Assembly).AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof (CartCommandService).GetTypeInfo().Assembly, typeof (ICartCommandService).GetTypeInfo().Assembly) .AsImplementedInterfaces(); var databaseInitializer = new MigrateToLatestVersion(new SampleDataSeeder()); builder.AddDataOnion(new DbContextConfig(configuration.GetConnectionString("DefaultConnection"), typeof(MusicStoreContext), databaseInitializer)); // Populate the container with services that were previously registered builder.Populate(services); builder.RegisterType<BaseRepository<Album, MusicStoreContext>>().As<IRepository<Album>>(); builder.RegisterType<BaseRepository<Artist, MusicStoreContext>>().As<IRepository<Artist>>(); builder.RegisterType<BaseRepository<Cart, MusicStoreContext>>().As<IRepository<Cart>>(); builder.RegisterType<BaseRepository<CartItem, MusicStoreContext>>().As<IRepository<CartItem>>(); builder.RegisterType<BaseRepository<Genre, MusicStoreContext>>().As<IRepository<Genre>>(); builder.RegisterType<BaseRepository<Order, MusicStoreContext>>().As<IRepository<Order>>(); builder.RegisterType<BaseRepository<OrderDetail, MusicStoreContext>>().As<IRepository<OrderDetail>>(); var container = builder.Build(); return container; }
// This method gets called by the runtime. Use this method to add services to the container public IServiceProvider ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); // Inject services to application. var mvcBuilder = services.AddMvc(); /*mvcBuilder.AddMvcOptions(option => { option.OutputFormatters.OfType<JsonOutputFormatter>() .First() .SerializerSettings .ContractResolver = new CamelCasePropertyNamesContractResolver(); }); */ // Create the Autofac container builder. var builder = new ContainerBuilder(); // Add any Autofac modules or registrations. builder.RegisterModule(new BusinessModule()); builder.RegisterModule(new SharedModule()); // Populate the services. builder.Populate(services); // Build the container. var container = builder.Build(); // Resolve and return the service provider. return container.Resolve<IServiceProvider>(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseServices(services => { // We add MVC here instead of in ConfigureServices. services.AddMvc(); // Create the Autofac container builder. var builder = new ContainerBuilder(); // Add any Autofac modules or registrations. builder.RegisterModule(new AutofacModule()); // Populate the services. builder.Populate(services); // Build the container. var container = builder.Build(); // Resolve and return the service provider. return container.Resolve<IServiceProvider>(); }); app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); }); }
public Container(IServiceCollection services) { // Create the container builder. autofacContainerBuilder = new Autofac.ContainerBuilder(); // Register dependencies, populate the services from // the collection, and build the container. If you want // to dispose of the container at the end of the app, // be sure to keep a reference to it as a property or field. //builder.RegisterType<MyType>().As<IMyTyHippe>(); //If nothing is using/calling a type in an assembly you are trying to load, //Load(...) will fail. The compiler will optimize the code so that unused dependencies //are removed. var assembly = Assembly.Load(new AssemblyName { Name = "Authentication.Container" }); autofacContainerBuilder.RegisterAssemblyModules(assembly); autofacContainerBuilder.Populate(services); autofacContainer = autofacContainerBuilder.Build(); serviceProvider = new AutofacServiceProvider(autofacContainer); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { #region Token Bearer services.AddJwtAuthentication(Path.Combine(_env.ContentRootPath, "./Security"), "RsaKey.json", "noobs", "http://leadisjourney.fr"); #endregion services.AddNHibernate(Configuration.GetConnectionString("type"), Configuration.GetConnectionString("DefaultConnection")); // Add framework services. services.AddMvc(); services.AddCors(option => option.AddPolicy("AllowAll", p => { p.AllowAnyOrigin(); p.AllowCredentials(); p.AllowAnyMethod(); p.AllowAnyHeader(); })); // Adding ioc Autofac var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(services); containerBuilder.RegisterModule<GlobalRegistration>(); var container = containerBuilder.Build(); return container.Resolve<IServiceProvider>(); }
public IServiceProvider ConfigureServices(IServiceCollection services) { var builder1 = new ContainerBuilder(); builder1.RegisterModule<TestModule>(); builder1.Populate(services); var container1 = builder1.Build(); var nonScopeOptions = container1.Resolve<IServiceProvider>() .GetService<Microsoft.Framework.OptionsModel.IOptions<RazorViewEngineOptions>>() .Options; Console.WriteLine("{0} Options", nonScopeOptions.ViewLocationExpanders.Count); Console.WriteLine(""); var builder2 = new ContainerBuilder(); builder2.Populate(services); var container2 = builder2.Build(); var scope = container2.BeginLifetimeScope((inner) => { inner.RegisterModule<TestModule>(); }).Resolve<IServiceProvider>(); var scopeOptions = scope .GetService<Microsoft.Framework.OptionsModel.IOptions<RazorViewEngineOptions>>() .Options; Console.WriteLine("{0} Options", scopeOptions.ViewLocationExpanders.Count); return container1.Resolve<IServiceProvider>(); }
public static IAppContainer GetAppContainer(IServiceCollection services) { var builder = new ContainerBuilder(); builder.RegisterModule<DefaultModule>(); builder.Populate(services); return new AppContainer(builder.Build()); }
protected override IServiceProvider CreateContainer() { var builder = new ContainerBuilder(); builder.Populate(TestServices.DefaultServices()); IContainer container = builder.Build(); return container.Resolve<IServiceProvider>(); }
/// <summary> /// 构建服务并设置本地程序平台的Resolver /// </summary> /// <param name="services">服务映射信息集合</param> /// <param name="assemblies">要检索的程序集集合</param> /// <returns>服务提供者</returns> protected override IServiceProvider BuildAndSetResolver(IServiceCollection services, Assembly[] assemblies) { ContainerBuilder builder = new ContainerBuilder(); builder.Populate(services); IContainer container = builder.Build(); LocalIocResolver.Container = container; Resolver = container.Resolve<IIocResolver>(); return Resolver.Resolve<IServiceProvider>(); }
private IContainer CreateIoCContainer(IServiceCollection services) { services.AddTransient<IEmailSender, EmailSender>(); var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(services); return containerBuilder.Build(); }
/// <summary> /// 构建服务并设置SignalR平台的Resolver /// </summary> /// <param name="services">服务映射信息集合</param> /// <param name="assemblies">要检索的程序集集合</param> protected override IServiceProvider BuildAndSetResolver(IServiceCollection services, Assembly[] assemblies) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterHubs().AsSelf().PropertiesAutowired(); builder.Populate(services); IContainer container = builder.Build(); IDependencyResolver resolver = new AutofacDependencyResolver(container); GlobalHost.DependencyResolver = resolver; return resolver.Resolve<IServiceProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 //public void ConfigureServices(IServiceCollection services) //{ // services.AddMvc(); // services.AddSingleton<IService<EmployeeInfo>, EmployeeInfoService>(); //} public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); var objectBuilder = new ContainerBuilder(); objectBuilder.RegisterModule<DependencyRegistrationModule>(); objectBuilder.Populate(services); var objectContainer = objectBuilder.Build(); return objectContainer.Resolve<IServiceProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddCustomPageCore(); var builder = new ContainerBuilder(); builder.Populate(services); var container = builder.Build(); _serviceProvider = container.Resolve<IServiceProvider>(); }
public IServiceProvider ConfigureServices(IServiceCollection services) { // Create the autofac container var builder = new ContainerBuilder(); builder.RegisterModule<TestModule>(); builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); }
protected override void Load(ContainerBuilder builder) { var services2 = new ServiceCollection(); services2.AddMvc(); services2.ConfigureRazorViewEngine(options => { options.ViewLocationExpanders.Add(new TestViewLocationExpander()); }); builder.Populate(services2); }
private static IContainer BuildContainer(IServiceCollection services) { var builder = new Autofac.ContainerBuilder(); builder.RegisterType <NpvCalculator>().As <INpvCalculator>(); builder.Populate(services); var container = builder.Build(); return(container); }
/// <summary> /// 构建服务并设置MVC平台的Resolver /// </summary> /// <param name="services">服务映射信息集合</param> /// <param name="assemblies">程序集集合</param> /// <returns>服务提供者</returns> protected override IServiceProvider BuildAndSetResolver(IServiceCollection services, Assembly[] assemblies) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(assemblies).AsSelf().PropertiesAutowired(); builder.RegisterFilterProvider(); builder.Populate(services); IContainer container = builder.Build(); IDependencyResolver resolver = new AutofacDependencyResolver(container); DependencyResolver.SetResolver(resolver); return resolver.GetService<IServiceProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); var builder = new Autofac.ContainerBuilder(); builder.RegisterType <UserRepository>().As <IUserRepository>(); builder.Populate(services); Container = builder.Build(); return(new AutofacServiceProvider(Container)); }
// Set up application services public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddTransient<HelloWorldBuilder>(); var builder = new ContainerBuilder(); builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); }
//// Use another IoC Container //public IServiceProvider ConfigureServices(IServiceCollection services) //{ // services.AddEntityFramework() // .AddSqlServer() // .AddDbContext<TodoItemAppContext>(); // services.AddMvc(); // //return this.ConfigureAutofac(services); // services.AddTransient<ITodoListProvider, TodoListProvider>(); // return services.BuildServiceProvider(); //} public IServiceProvider ConfigureAutofac(IServiceCollection services) { // Pull this out into your other methods or modules if it gets too big var builder = new ContainerBuilder(); builder.RegisterType<TodoListProvider>().As<ITodoListProvider>(); // Register the services that were previously registered with the built in DI builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); }
/// <summary> /// 构建服务并设置WebApi平台的Resolver /// </summary> /// <param name="services">服务映射信息集合</param> /// <param name="assemblies">要检索的程序集集合</param> /// <returns>服务提供者</returns> protected override IServiceProvider BuildAndSetResolver(IServiceCollection services, Assembly[] assemblies) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterApiControllers(assemblies).AsSelf().PropertiesAutowired(); builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); builder.RegisterWebApiModelBinderProvider(); builder.Populate(services); IContainer container = builder.Build(); IDependencyResolver resolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = resolver; return (IServiceProvider)resolver.GetService(typeof(IServiceProvider)); }
private IServiceProvider ConfigAutofacDI(IServiceCollection services) { var builder = new Autofac.ContainerBuilder(); builder.RegisterType <RequestIdFactory>().As <IRequestIdFactory>().SingleInstance(); builder.RegisterType <RequestId>().As <IRequestId>(); builder.Populate(services); this.ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(this.ApplicationContainer)); }
public static IServiceProvider Register(IServiceCollection services) { // force runtime to reference BookStore.EF6.MVC6 project so that Types.Referenced can find it var bookStoreEF6Services = typeof(BookStore.EF6.Services.BookReader); var builder = new ContainerBuilder(); builder.RegisterSource(new ContravariantRegistrationSource()); Types.Referenced.KindOf("Services") .Classes() .ForAll(t => { builder .RegisterType(t) .AsImplementedInterfaces() .InstancePerLifetimeScope(); }); Types.Referenced.KindOf("Services.Singletons") .Classes() .ForAll(t => { builder .RegisterType(t) .AsImplementedInterfaces() .SingleInstance(); }); Types.Referenced.KindOf("Services.Transient") .Classes() .ForAll(t => { builder .RegisterType(t) .AsImplementedInterfaces() .InstancePerDependency(); }); Types.Referenced.With<MixinAttribute>() .ForAll(t => builder .RegisterType(Mixin.Emit(t)) .As(t)); builder.RegisterType<ServiceProvider>() .AsImplementedInterfaces(); //Populate the container with services that were previously registered builder.Populate(services); var container = builder.Build(); Event.Subscribe(new EventDispatcher(container.Resolve<IServiceProvider>())); return container.Resolve<IServiceProvider>(); }
protected override void Load(ContainerBuilder builder) { Console.WriteLine("Registering Module"); var services2 = new ServiceCollection(); services2.AddMvc(); services2.ConfigureRazorViewEngine(options => { Console.WriteLine("Registering TestViewLocationExpander"); options.ViewLocationExpanders.Add(new TestViewLocationExpander()); }); builder.Populate(services2); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services .AddMvcCore() .AddJsonFormatters(); // Add Autofac var builder = new ContainerBuilder(); builder.RegisterModule<DefaultModule>(); builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAutoMapper(); AutoMapperProfile.config(); var builder = new Autofac.ContainerBuilder(); builder.Populate(services); builder.RegisterModule(new AutoFacResolver(Configuration.GetConnectionString("DefaultConnection"))); var container = builder.Build(); return(container.Resolve <IServiceProvider>()); }
public IServiceProvider ConfigureServices(IServiceCollection services) { var containerBuilder = new ContainerBuilder(); // note Type.Assembly doesn't exist; use Type.GetTypeInfo().Assembly containerBuilder.RegisterAssemblyModules(typeof (Startup).GetTypeInfo().Assembly); containerBuilder.Populate(services); var container = containerBuilder.Build(); return container.Resolve<IServiceProvider>(); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddCaching(); services.AddSession(); services.AddMvc(options => { options.Filters.Add(typeof(PassThroughAttribute), order: 17); options.Filters.Add(new FormatFilterAttribute()); }) .AddXmlDataContractSerializerFormatters() .AddViewLocalization(LanguageViewLocationExpanderFormat.SubFolder); services.AddSingleton<PassThroughAttribute>(); services.AddSingleton<UserNameService>(); services.AddTransient<ITestService, TestService>(); var applicationEnvironment = services.BuildServiceProvider().GetRequiredService<IApplicationEnvironment>(); var configurationPath = Path.Combine(applicationEnvironment.ApplicationBasePath, "config.json"); // Set up configuration sources. var configBuilder = new ConfigurationBuilder() .AddJsonFile(configurationPath) .AddEnvironmentVariables(); var configuration = configBuilder.Build(); var diSystem = configuration["DependencyInjection"]; if (!string.IsNullOrEmpty(diSystem) && diSystem.Equals("AutoFac", StringComparison.OrdinalIgnoreCase)) { _autoFac = true; // Create the autofac container var builder = new ContainerBuilder(); // Create the container and use the default application services as a fallback builder.Populate(services); builder.RegisterModule<MonitoringModule>(); var container = builder.Build(); return container.Resolve<IServiceProvider>(); } else { return services.BuildServiceProvider(); } }
/// <summary> /// Registers dependencies. /// </summary> /// <param name="services"><see cref="IServiceCollection"/> instance.</param> /// <param name="env"><see cref="IHostingEnvironment"/> instance.</param> /// <param name="configuration"><see cref="IConfiguration"/> instance.</param> /// <returns>Returns the <see cref="IContainer"/> instance.</returns> public static IContainer Register(IServiceCollection services, IHostingEnvironment env, IConfiguration configuration) { var builder = new ContainerBuilder(); RegisterAppSettings(builder, env, configuration); RegisterLoaders(builder); RegisterHelpers(builder); RegisterServices(builder); builder.Populate(services); var container = builder.Build(); return container; }
public static IServiceProvider Configure(IServiceCollection serviceCollection) { var containerBuilder = new Autofac.ContainerBuilder(); containerBuilder.Populate(serviceCollection); Register(containerBuilder); var container = containerBuilder.Build(); var serviceProvider = new AutofacServiceProvider(container); return(serviceProvider); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { Console.WriteLine("Entry ConfigureServices"); Log.Debug("Entry ConfigureServices"); // Add framework services. services.AddMvc(); var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterModule(new AutoFacModule()); containerBuilder.Populate(services); var container = containerBuilder.Build(); return container.Resolve<IServiceProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Add Entity Framework services to the services container. services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationContext>() .AddDefaultTokenProviders(); // Configure the options for the authentication middleware. // You can add options for Google, Twitter and other middleware as shown below. // For more information see http://go.microsoft.com/fwlink/?LinkID=532715 /*services.Configure<FacebookAuthenticationOptions>(options => { options.AppId = Configuration["Authentication:Facebook:AppId"]; options.AppSecret = Configuration["Authentication:Facebook:AppSecret"]; }); services.Configure<MicrosoftAccountAuthenticationOptions>(options => { options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"]; options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]; });*/ // Add MVC services to the services container. services.AddMvc(); services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings")); // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. // services.AddWebApiConventions(); // Register application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); var cb = new ContainerBuilder(); cb.Populate(services); cb.RegisterType<Log>().As<ILog>().InstancePerDependency(); cb.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope(); var container = cb.Build(); return container.Resolve<IServiceProvider>(); }
/// <summary> /// 创建容器生成器 /// </summary> /// <param name="services">服务集合</param> /// <param name="actionBefore">注册前执行的操作</param> /// <param name="configs">依赖配置</param> public ContainerBuilder CreateBuilder(IServiceCollection services, Action <ContainerBuilder> actionBefore, params IConfig[] configs) { if (_builder == null) { _builder = new ContainerBuilder(); } actionBefore?.Invoke(_builder); foreach (var config in configs) { _builder.RegisterModule(config); } if (services != null) { _builder.Populate(services); } return(_builder); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); services.AddSession(options => { // Set a short timeout for easy testing. options.IdleTimeout = TimeSpan.FromMinutes(60); options.Cookie.HttpOnly = true; // Make the session cookie essential options.Cookie.IsEssential = true; }); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "dd/MM/yyyy HH:mm:ss"; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); services.AddHttpContextAccessor(); var builder = new Autofac.ContainerBuilder(); //builder.RegisterType<OperationManager>().As<IOperationManager>(); builder.RegisterType <HostingEnvironment>().As <IHostingEnvironment>(); builder.RegisterType <CustomSiteMapModule>(); //services.AddSingleton<ILoggerManager, LoggerManager>(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); builder.Populate(services); var container = builder.Build(); return(container.Resolve <IServiceProvider>()); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); var builder = new Autofac.ContainerBuilder(); // note: Jack tried to register interface and abstract version of // WeatherService. For whatever reason autofac does not work. // autofac only works with classes builder.RegisterType <WeatherService>().As <WeatherService>(); builder.Populate(services); var container = builder.Build(); return(container.Resolve <IServiceProvider>()); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); }); services.AddOptions(); services.Configure <BlogAppSettingConfig>(Configuration.GetSection("BlogAppSetting")); //services.AddDbContext<DataContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnectionSqlite"))); //services.AddDbContext<DataContext>(options=> options.UseMySql(@"Server=127.0.0.1;database=Blogmy;uid=root;pwd=root")); services.AddMvc(); var containerBuilder = new Autofac.ContainerBuilder(); containerBuilder.RegisterModule <AutofacModule>(); containerBuilder.Populate(services); var container = containerBuilder.Build(); return(new AutofacServiceProvider(container)); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <MyTaskDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection") , b => b.MigrationsAssembly("AddressBookAPI"))); services.AddDefaultIdentity <IdentityUser>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores <MyTaskDbContext>(); ESCMapperConfiguration.ConfigMapper(services); services.AddAutoMapper(typeof(Startup)); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Add Autofac var containerBuilder = new Autofac.ContainerBuilder(); containerBuilder.RegisterModule <AutoFacContainerModule>(); containerBuilder.Populate(services); var container = containerBuilder.Build(); return(new AutofacServiceProvider(container)); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Maintain property names during serialization. See: // https://github.com/aspnet/Announcements/issues/194 services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()) ; ConfigureRazorAndCompression(services); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSignalR(); // Add Kendo UI services to the services container services.AddKendo(); // services.AddScoped<NLoggingAttribute>(); services.AddAutoMapper(); services.AddHostedService <TimedHostedService>(); services.AddAuthentication(options => { options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.AccessDeniedPath = new PathString("/AccessDenied"); options.LoginPath = new PathString("/UserAccount"); options.ExpireTimeSpan = TimeSpan.FromSeconds(60000); options.SlidingExpiration = true; options.Events = new CookieAuthenticationEvents() { OnRedirectToAccessDenied = (ctx) => { var request = ctx.HttpContext.Request.Path; _logger.LogError("Access Denied to Path" + request.Value); ctx.Response.Redirect(ctx.RedirectUri); return(Task.CompletedTask); } }; }); services.AddHsts(options => { options.Preload = true; options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(60); options.ExcludedHosts.Add("example.com"); options.ExcludedHosts.Add("www.example.com"); }); services.AddAntiforgery(options => { // new API options.Cookie.Name = "AntiforgeryCookie"; options.Cookie.Path = "/"; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; }); services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 443; }); ConfigureMiniProfier(services); ConfigureWebOptimer(services); var builder = new Autofac.ContainerBuilder(); builder.RegisterAssemblyModules(System.Reflection.Assembly.GetExecutingAssembly()); builder.Populate(services); var sqlConnection = Configuration.GetValue <string>("DBConnection"); builder.RegisterModule(new ServiceDIContainer(sqlConnection)); builder.Register(c => { return(Bus.Factory.CreateUsingRabbitMq(sbc => sbc.Host(new Uri("rabbitmq://localhost:/"), h => { h.Username("guest"); h.Password("guest"); }) )); }) .As <IBusControl>() .As <IBus>() .As <IPublishEndpoint>() .SingleInstance(); this.ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(this.ApplicationContainer)); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); services.AddControllers(); services.AddControllers() .AddNewtonsoftJson(opt => { opt.SerializerSettings.Error = (_, args) => { Console.WriteLine(args.ErrorContext.Error); }; opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; } ); var settings = Configuration.Get <Infrastructure.CrocusoftProjeSettings>(); services.Configure <Infrastructure.CrocusoftProjeSettings>(Configuration); // Add framework services. services.AddMvc(options => { options.Filters.Add(typeof(Api.Infrastructure.ErrorHandling.HttpGlobalExceptionFilter)); }) .AddControllersAsServices(); services.AddEntityFrameworkSqlServer() .AddDbContext <Infrastructure.Database.CrocusoftProjeDbContext>(options => { options.UseSqlServer(settings.ConnectionString, sqlOptions => { sqlOptions.MigrationsAssembly("Parla.Infrastructure.Migrations"); sqlOptions.EnableRetryOnFailure(10, TimeSpan.FromSeconds(3), new List <int>()); }); } ); ConfigureSwagger(services); ConfigureJwtAuthentication(services, settings); // Add application services. services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddOptions(); //configure Autofac var container = new Autofac.ContainerBuilder(); container.Populate(services); container.RegisterModule(new Api.Infrastructure.AutofacModules.MediatorModule()); container.RegisterModule(new Api.Infrastructure.AutofacModules.ApplicationModule()); return(new AutofacServiceProvider(container.Build())); }