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


C# IServiceCollection.AddDbContext方法代码示例

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


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

示例1: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            var useInMemoryStore = !_platform.IsRunningOnWindows
                || _platform.IsRunningOnMono
                || _platform.IsRunningOnNanoServer;

            // Add EF services to the services container
            if (useInMemoryStore)
            {
                services.AddDbContext<MusicStoreContext>(options =>
                            options.UseInMemoryDatabase());
            }
            else
            {
                services.AddDbContext<MusicStoreContext>(options =>
                            options.UseSqlServer(Configuration[StoreConfig.ConnectionStringKey.Replace("__",":")]));
            }

            // Add Identity services to the services container
            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
                    {
                        options.Cookies.ApplicationCookie.AccessDeniedPath = "/Home/AccessDenied";
                    })
                    .AddEntityFrameworkStores<MusicStoreContext>()
                    .AddDefaultTokenProviders();


            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                {
                    builder.WithOrigins("http://example.com");
                });
            });

            // Add MVC services to the services container
            services.AddMvc();

            // Add memory cache services
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();

            // Add session related services.
            services.AddSession();

            // Add the system clock service
            services.AddSingleton<ISystemClock, SystemClock>();

            // Configure Auth
            services.AddAuthorization(options =>
            {
                options.AddPolicy(
                    "ManageStore",
                    authBuilder => {
                        authBuilder.RequireClaim("ManageStore", "Allowed");
                    });
            });
        }
开发者ID:masterMuTou,项目名称:MusicStore,代码行数:60,代码来源:Startup.cs

示例2: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            //Sql client not available on mono
            var useInMemoryStore = !_runtimeEnvironment.OperatingSystem.Equals("Windows", StringComparison.OrdinalIgnoreCase);

            // Add EF services to the services container
            if (useInMemoryStore)
            {
                services.AddDbContext<MusicStoreContext>(options =>
                            options.UseInMemoryDatabase());
            }
            else
            {
                services.AddDbContext<MusicStoreContext>(options =>
                            options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
            }

            // Add Identity services to the services container
            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
                    {
                        options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied");
                    })
                    .AddEntityFrameworkStores<MusicStoreContext>()
                    .AddDefaultTokenProviders();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                {
                    builder.WithOrigins("http://example.com");
                });
            });

            // Add MVC services to the services container
            services.AddMvc();

            //Add InMemoryCache
            services.AddSingleton<IMemoryCache, MemoryCache>();

            // Add session related services.
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddSession();

            // Add the system clock service
            services.AddSingleton<ISystemClock, SystemClock>();

            // Configure Auth
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ManageStore", new AuthorizationPolicyBuilder().RequireClaim("ManageStore", "Allowed").Build());
            });
        }
开发者ID:masterMuTou,项目名称:MusicStore,代码行数:55,代码来源:StartupSocialTesting.cs

示例3: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            // Add EF services to the services container
            if (_platform.UseInMemoryStore)
            {
                services.AddDbContext<MusicStoreContext>(options =>
                            options.UseInMemoryDatabase());
            }
            else
            {
                services.AddDbContext<MusicStoreContext>(options =>
                            options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
            }

            // Add Identity services to the services container
            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<MusicStoreContext>()
                    .AddDefaultTokenProviders();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                {
                    builder.WithOrigins("http://example.com");
                });
            });

            // Add MVC services to the services container
            services.AddMvc();

            // Add memory cache services
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();

            // Add session related services.
            services.AddSession();

            // Add the system clock service
            services.AddSingleton<ISystemClock, SystemClock>();

            // Configure Auth
            services.AddAuthorization(options =>
            {
                options.AddPolicy(
                    "ManageStore",
                    authBuilder =>
                    {
                        authBuilder.RequireClaim("ManageStore", "Allowed");
                    });
            });
        }
开发者ID:CarlSosaDev,项目名称:MusicStore,代码行数:53,代码来源:StartupOpenIdConnect.cs

示例4: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc(options =>
                {
                    options.RespectBrowserAcceptHeader = true;
                })
                    .AddXmlDataContractSerializerFormatters();

            var connection = @"Server=(localdb)\mssqllocaldb;Database=SandboxCore;Trusted_Connection=True;";
            services.AddDbContext<CommandDbContext>(options => options.UseSqlServer(connection));
            services.AddDbContext<QueryDbContext>(options => options.UseSqlServer(connection));
        }
开发者ID:RossWhitehead,项目名称:SandboxCore,代码行数:14,代码来源:Startup.cs

示例5: ConfigureServices

        // 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)
        {
            //try
            //{
            //    var connectionString = Configuration["database:connection"];

            //    System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);
            //    conn.Open();
            //    conn.Close();
            //}
            //catch (System.Exception ex)
            //{

            //    throw;
            //}

            services.AddMvc();

            services.AddDbContext<OdeToFoodDbContext>(options => options.UseSqlServer(Configuration["database:connection"]));

            services.AddSingleton(provider => Configuration);
            services.AddSingleton<IGreeter, Greeter>();
            //services.AddScoped<IRestaurantData, InMemoryRestaurantData>();
            services.AddScoped<IRestaurantData, SqlRestaurantData>();
        }
开发者ID:Geo-Comm,项目名称:Sample_dotnetcoremvc,代码行数:27,代码来源:Startup.cs

示例6: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc(o => o.Conventions.Add(new FeatureConvention()))
                .AddRazorOptions(options =>
                {
                    // {0} - Action Name
                    // {1} - Controller Name
                    // {2} - Area Name
                    // {3} - Feature Name
                    options.ViewLocationFormats.Clear();
                    options.ViewLocationFormats.Add("/Features/{3}/{1}/{0}.cshtml");
                    options.ViewLocationFormats.Add("/Features/{3}/{0}.cshtml");
                    options.ViewLocationFormats.Add("/Features/Shared/{0}.cshtml");

                    options.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
                });

            services.AddTransient<IEmailSender, MessageServices>();
            services.AddTransient<ISmsSender, MessageServices>();

            var builder = services.AddDeveloperIdentityServer()
                .AddInMemoryScopes(Scopes.Get())
                .AddInMemoryClients(Clients.Get())
                .AddAspNetIdentity<ApplicationUser>();
        }
开发者ID:gabrewer,项目名称:gabMileage,代码行数:33,代码来源:Startup.cs

示例7: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var s = services.FirstOrDefault(x => x.ServiceType == typeof(IHostingEnvironment));
            var env = s.ImplementationInstance as IHostingEnvironment;

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite([email protected]"Data Source={env.ContentRootPath}/j64.AlarmServer.db"));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("ArmDisarm", policy => policy.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "ArmDisarm"));
            });

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            // Add a single instance of the alarm system
            var alarmSystem = Repository.AlarmSystemRepository.Get();
            alarmSystem.ZoneChange += SmartThingsRepository.AlarmSystem_ZoneChange;
            alarmSystem.PartitionChange += SmartThingsRepository.AlarmSystem_PartitionChange;
            alarmSystem.StartSession();
            services.AddSingleton<AlarmSystem>(alarmSystem);
        }
开发者ID:joejarvis64,项目名称:j64.AlarmServer,代码行数:32,代码来源:Startup.cs

示例8: ConfigureServices

 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     var connection = "Filename=netcorebbs.db";
     services.AddDbContext<DataContext>(options => options.UseSqlite(connection));
     // Add framework services.
     services.AddMvc();
 }
开发者ID:ciker,项目名称:NETCoreBBS,代码行数:8,代码来源:Startup.cs

示例9: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddDbContext<ApplicationDbContext>(options => options
                    .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services
                .AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services
                .AddMvc()
                .AddTypedRouting(routes => routes
                    .Get("CustomController/{action}", route => route.ToController<ExpressionsController>())
                    .Get("CustomContact", route => route.ToAction<HomeController>(a => a.Contact()))
                    .Get("WithParameter/{id}", route => route.ToAction<HomeController>(a => a.Index(With.Any<int>())))
                    .Get("Async", route => route.ToAction<AccountController>(a => a.LogOff()))
                    .Get("Named", route => route
                        .ToAction<AccountController>(a => a.Register(With.Any<string>()))
                        .WithName("CustomName"))
                    .Add("Constraint", route => route
                        .ToAction<AccountController>(c => c.Login(With.Any<string>()))
                        .WithActionConstraints(new HttpMethodActionConstraint(new[] { "PUT" })))
                    .Add("MultipleMethods", route => route
                        .ToAction<HomeController>(a => a.About())
                        .ForHttpMethods("GET", "POST")));
            
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }
开发者ID:ivaylokenov,项目名称:AspNet.Mvc.TypedRouting,代码行数:31,代码来源:Startup.cs

示例10: ConfigureServices

 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     var connection = @"Server=(localdb)\mssqllocaldb;Database=SurveyApp;Trusted_Connection=True;";
     services.AddDbContext<SurveyAppContext>(options => options.UseSqlServer(connection));
     // Add framework services.
     services.AddMvc();
 }
开发者ID:13pape,项目名称:SurveyApp,代码行数:8,代码来源:Startup.cs

示例11: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
              services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

              services.AddMemoryCache();

              services.AddMvc()
              .AddJsonOptions(options =>
                  options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

              services.Configure<AppSettings>(settings => settings = Configuration.GetSection("AppSettings") as AppSettings);

              // Add application services.
              services.AddSingleton<RawDataRepository>()
              .AddSingleton<CacheDataRepository>()
              .AddSingleton<GlobalCacheRepository>()
              //.AddSingleton<LocalCacheRepository>()
              //.AddSingleton<MasterDataService>()
              //.AddSingleton<CardService>()
              //.AddSingleton<TreasureService>()
              //.AddSingleton<CombatService>()
              //.AddSingleton<FamilyService>()
              //.AddSingleton<AccountService>()
              //.AddSingleton<SecurityService>()
              .AddSingleton<SummaryService>()
              .AddSingleton<MasterDataService>()
              .AddSingleton<MasterDataRepository>();
        }
开发者ID:huytrongnguyen,项目名称:MoonlightGarden,代码行数:31,代码来源:Startup.cs

示例12: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity<User, IdentityRole>(options =>
            {
                options.Password = new PasswordOptions() {
                    RequireNonAlphanumeric = false,
                    RequireUppercase=false
                };
            }).AddEntityFrameworkStores<DataContext>().AddDefaultTokenProviders();
            // Add framework services.
            services.AddMvc();

            services.AddTransient<IUserServices, UserServices>();
            services.AddTransient<UserServices>();
            services.AddMemoryCache();
            services.AddAuthorization(options =>
            {
                options.AddPolicy(
                    "Admin",
                    authBuilder =>
                    {
                        authBuilder.RequireClaim("Admin", "Allowed");
                    });
            });
        }
开发者ID:yaozhenfa,项目名称:NETCoreBBS,代码行数:27,代码来源:Startup.cs

示例13: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry(Configuration);

            if (_isDevEnvironment)
            {
                services.AddHaufwerk(new HaufwerkOptions("Haufwerk", "http://localhost:5000")
                {
                    LogLocalRequests = true
                });
            }
            else
            {
                services.AddHaufwerk(new HaufwerkOptions("Haufwerk", "https://haufwerk.sachsenhofer.com")
                {
                    LogLocalRequests = true
                });
            }

            services.AddMvc();
            services.AddDbContext<Db>(options =>
            {
                options.UseSqlServer(Configuration["Database:ConnectionString"]);
            });
        }
开发者ID:saxx,项目名称:Haufwerk,代码行数:25,代码来源:Startup.cs

示例14: ConfigureServices

        // 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.AddSingleton(_config);

            services.AddDbContext<CPPlannerContext>();

            services.AddTransient<CPPlannerContextSeedData>();

            services.AddScoped<ICPPlannerRepository, CPPlannerRepository>();

            services.AddIdentity<CPPlannerUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail = true;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";     // Forward user to url if not authorized
            })
            .AddEntityFrameworkStores<CPPlannerContext>();

            services.AddMvc(config =>
            {
                if (_env.IsEnvironment("Production"))   // or _env.IsProduction(). This uses default. If you want to set your own prod env, use: ASPNETCORE_ENVIRONMENT=Production
                {
                    config.Filters.Add(new RequireHttpsAttribute());
                }
            })
            .AddJsonOptions(config =>
            {
                config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        }
开发者ID:CPPlanner,项目名称:CPPlanner,代码行数:32,代码来源:Startup.cs

示例15: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TimedJobSiteContext>(x => x.UseInMemoryDatabase());

            services.AddTimedJob()
                .AddEntityFrameworkDynamicTimedJob<TimedJobSiteContext>();
        }
开发者ID:yonglehou,项目名称:dotNETCore-Extensions,代码行数:7,代码来源:Startup.cs


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