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


C# IServiceCollection.AddEntityFrameworkSqlServer方法代码示例

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


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

示例1: ConfigureServices

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

            services
                .AddIdentity<ApplicationUser, ApplicationRole>(options =>
                {
                    options.Password.RequiredLength = 6;
                    options.Password.RequireDigit = false;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = false;

                    options.Lockout.AllowedForNewUsers = false;

                    options.SignIn.RequireConfirmedEmail = false;
                    options.SignIn.RequireConfirmedPhoneNumber = false;
                })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()
                .AddUserStore<MyUserStore<ApplicationUser, ApplicationRole, ApplicationDbContext, string>>()
                .AddRoleStore<MyRoleStore<ApplicationRole, ApplicationDbContext, string>>();

            // Add framework services.
            services.AddMvc();
        }
开发者ID:kosmakoff,项目名称:WebApiWithAuth,代码行数:28,代码来源:Startup.cs

示例2: ConfigureServices

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

            // We re-register the Scenarios as an instance singleton here to avoid it being created again due to the
            // registration done in Program.Main
            services.AddSingleton(Scenarios);

            // Common DB services
            services.AddSingleton<IRandom, DefaultRandom>();
            services.AddSingleton<ApplicationDbSeeder>();
            services.AddEntityFrameworkSqlServer()
                .AddDbContext<ApplicationDbContext>();

            if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
            {
                // TODO: Add support for plugging in different DbProviderFactory implementations via configuration
                services.AddSingleton<DbProviderFactory>(SqlClientFactory.Instance);
            }

            if (Scenarios.Any("Ef"))
            {
                services.AddScoped<EfDb>();
            }

            if (Scenarios.Any("Raw"))
            {
                services.AddScoped<RawDb>();
            }

            if (Scenarios.Any("Dapper"))
            {
                services.AddScoped<DapperDb>();
            }

            if (Scenarios.Any("Fortunes"))
            {
                services.AddWebEncoders();
            }

            if (Scenarios.Any("Mvc"))
            {
                var mvcBuilder = services
                    .AddMvcCore()
                    //.AddApplicationPart(typeof(Startup).GetTypeInfo().Assembly)
                    .AddControllersAsServices();

                if (Scenarios.MvcJson)
                {
                    mvcBuilder.AddJsonFormatters();
                }

                if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes"))
                {
                    mvcBuilder
                        .AddViews()
                        .AddRazorViewEngine();
                }
            }
        }
开发者ID:sumeetchhetri,项目名称:FrameworkBenchmarks,代码行数:60,代码来源:Startup.cs

示例3: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEntityFrameworkSqlServer()
                    .AddDbContext<MuztacheStore>(options => options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Muztache;Trusted_Connection=True;"));
                    //.AddDbContext<MuztacheStore>(options => options.UseSqlServer(@"Data Source=n9libpbrtl.database.windows.net;Initial Catalog=Muztache_db;Integrated Security=False;User ID=DataReader;Password=Tig3rBl00d;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"));

            // Add framework services.
            services.AddMvc();

            services.AddTransient<SampleDataInitializer>();
            services.AddTransient<BlobService>();
        }
开发者ID:Lejdholt,项目名称:Muztache,代码行数:13,代码来源:Startup.cs

示例4: 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.AddMvc();
            services.AddEntityFrameworkSqlServer().AddDbContext<OdeToFoodDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("OdeToFoodDatabase")));
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<OdeToFoodDbContext>()
                .AddDefaultTokenProviders();

            services.AddSingleton(povider => Configuration);
            services.AddSingleton<IGreeter, Greeter>();
            services.AddScoped<IRestaurantData, SqlResaurantData>();
        }
开发者ID:Candace-Williford,项目名称:PluralSight-OdeToFood,代码行数:14,代码来源:Startup.cs

示例5: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.TryAddScoped<ICoreModelMapper, SqlServerCoreModelMapper>();

            services.AddEntityFrameworkSqlServer()
              .AddDbContext<CoreDbContext>((serviceProvider, options) =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                       .UseInternalServiceProvider(serviceProvider)
                       );

            //services.AddDbContext<CoreDbContext>(options =>
            //        options.UseSqlServer(Configuration["Data:EF7ConnectionOptions:ConnectionString"])
            //        );
        }
开发者ID:ReinhardHsu,项目名称:cloudscribe,代码行数:14,代码来源:Startup.cs

示例6: ConfigureServices

        // This method gets called by a runtime.
        // Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyNames.RequireSurveyCreator,
                    policy =>
                    {
                        policy.AddRequirements(new SurveyCreatorRequirement());
                        policy.RequireAuthenticatedUser(); // Adds DenyAnonymousAuthorizationRequirement 
                        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                    });
                options.AddPolicy(PolicyNames.RequireSurveyAdmin,
                    policy =>
                    {
                        policy.AddRequirements(new SurveyAdminRequirement());
                        policy.RequireAuthenticatedUser(); // Adds DenyAnonymousAuthorizationRequirement 
                        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                    });
            });

            // Add Entity Framework services to the services container.
            services.AddEntityFrameworkSqlServer()
                .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetSection("Data")["SurveysConnectionString"]));

            services.AddScoped<TenantManager, TenantManager>();
            services.AddScoped<UserManager, UserManager>();

            services.AddMvc();

            services.AddScoped<ISurveyStore, SqlServerSurveyStore>();
            services.AddScoped<IQuestionStore, SqlServerQuestionStore>();
            services.AddScoped<IContributorRequestStore, SqlServerContributorRequestStore>();
            services.AddSingleton<IAuthorizationHandler>(factory =>
            {
                var loggerFactory = factory.GetService<ILoggerFactory>();
                return new SurveyAuthorizationHandler(loggerFactory.CreateLogger<SurveyAuthorizationHandler>());
            });

            //
            //http://stackoverflow.com/questions/37371264/asp-net-core-rc2-invalidoperationexception-unable-to-resolve-service-for-type/37373557
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //
        }
开发者ID:mspnp,项目名称:multitenant-saas-guidance,代码行数:45,代码来源:Startup.cs

示例7: 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)
        {
            //mvc
            services.AddMvc().AddJsonOptions(opt=>
            {
                //json camel case options
                opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.AddLogging();

            services.AddEntityFrameworkSqlServer().AddDbContext<WorldContext>();

            services.AddIdentity<WorldUser, IdentityRole>(config=> {
                config.User.RequireUniqueEmail = true;
                config.Password.RequiredLength = 6;
                config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
                config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = context =>
                    {
                        if(context.Request.Path.StartsWithSegments("/api") && 
                        context.Response.StatusCode == (int)HttpStatusCode.OK)
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }

                        return Task.FromResult(0);
                    }
                };
            }).AddEntityFrameworkStores<WorldContext>();

            //change out with real mail service in production
            services.AddScoped<CoordService>();
            services.AddScoped<IMailService, DebugMailService>();
            services.AddScoped<IWorldRepository, WorldRepository>();
            services.AddScoped<WorldContextSeedData>();
        }
开发者ID:trevorjedsmith,项目名称:TheWorld,代码行数:45,代码来源:Startup.cs

示例8: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                config.Filters.Add(new DivineActionFilter());
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;

            });

            services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                        .AllowAnyMethod()
                                                                         .AllowAnyHeader()));

            services.AddSingleton<IDivineLogger, DivineLogger<SqlDataStore>>((s) =>
            {
                var folderPath = ApplicationBasePath + Configuration["AppSettings:Logs"];
                var appID = new Guid(Configuration["AppSettings:LoggerAppID"]);
                var dbConnString = Configuration["Data:DivineConnectionstring"];
                var sbConnString = Configuration["Data:ServiceBusConnection"];
                return new DivineLogger<SqlDataStore>(new SqlDataStore(dbConnString, sbConnString), appID);
            });
            services.AddScoped<IRepository<Member>, MembersRepository>();
            services.AddScoped<IRepository<DivineMessage>, MessageRepository>();
            services.AddScoped<IRepository<Attendance>, AttendanceRepository>();
            services.AddScoped<ILookupRepository, LookupRepository>();
            services.AddSingleton<IMemoryCache, MemoryCache>();
            services.AddScoped<IDivineRepositories, DivineRepositories>();
            services.AddSingleton<ICommunicationService, TwilioCommunicationService>((c) =>
           {

               string accountSid = Configuration["AppSettings:TwilioAccountSid"],
                       authToken = Configuration["AppSettings:TwilioAuthToken"],
                             url = Configuration["AppSettings:TwilioVoiceMessageUri"];

               return new TwilioCommunicationService(accountSid, authToken, url);
           });
            services.AddSingleton<IGeocoder, GoogleGeocoder>((s) =>
              {
                  var apiKey = Configuration["AppSettings:GoogleApiKey"];
                  return new GoogleGeocoder(apiKey);
              });
            services.AddScoped<SeedData>();
            services.AddSingleton<IDialog<DivineBotRequest>, DivineBotDialog>();

            // services.AddLogging();
            //services.AddCaching();
            /*
             * No database provider has been configured for this DbContext. 
             * A provider can be configured by overriding the DbContext.OnConfiguring 
             * method or by using AddDbContext on the application service provider. 
             * If AddDbContext is used, then also ensure that your DbContext 
             * type accepts a DbContextOptions<TContext> object in its constructor 
             * and passes it to the base constructor for DbContext.
             * */
            services.AddSession();
            services.AddEntityFrameworkSqlServer()
                .AddDbContext<DivineContext>(optionsBuilder =>
                {
                    var connString = Configuration["Data:DivineConnectionstring"];
                   
                    optionsBuilder.UseSqlServer(connString);
                });
            //          services.AddDbContext<ApplicationDbContext>(options =>
            //options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity<ApplicationUser, IdentityRole>(o =>
                {
                    o.Password.RequireDigit = false;
                    o.Password.RequireLowercase = false;
                    o.Password.RequireUppercase = false;
                    o.Password.RequiredLength = 6;

                    // if we are accessing the /api and an unauthorized request is made
                    // do not redirect to the login page, but simply return "Unauthorized"
                    o.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
                    {
                        OnRedirectToLogin = ctx =>
                        {
                            if (ctx.Request.Path.StartsWithSegments("/api"))
                                ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            else
                                ctx.Response.Redirect(ctx.RedirectUri);

                            return System.Threading.Tasks.Task.FromResult(0);
                        }
                    };
                
                }).AddEntityFrameworkStores<DivineContext>()
                  .AddDefaultTokenProviders();

            // Register the OpenIddict services, including the default Entity Framework stores.
            services.AddOpenIddict<ApplicationUser, DivineContext>()
                // Enable the token endpoint (required to use the password flow).
                .EnableTokenEndpoint("/connect/token")

//.........这里部分代码省略.........
开发者ID:mgolois,项目名称:DivineChMS,代码行数:101,代码来源:Startup.cs

示例9: ConfigureServices

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

            // We re-register the Scenarios as an instance singleton here to avoid it being created again due to the
            // registration done in Program.Main
            services.AddSingleton(Scenarios);

            // Common DB services
            services.AddSingleton<IRandom, DefaultRandom>();
            services.AddSingleton<ApplicationDbSeeder>();
            services.AddEntityFrameworkSqlServer()
                .AddDbContext<ApplicationDbContext>();
            
            if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
            {
                services.AddSingleton<DbProviderFactory>((provider) => {
                    var settings = provider.GetRequiredService<IOptions<AppSettings>>().Value;

                    if (settings.Database == DatabaseServer.PostgreSql)
                    {
                        return NpgsqlFactory.Instance;
                    }
                    else
                    {
                        return SqlClientFactory.Instance;
                    }
                });
            }

            if (Scenarios.Any("Ef"))
            {
                services.AddScoped<EfDb>();
            }

            if (Scenarios.Any("Raw"))
            {
                services.AddScoped<RawDb>();
            }

            if (Scenarios.Any("Dapper"))
            {
                services.AddScoped<DapperDb>();
            }

            if (Scenarios.Any("Fortunes"))
            {
                var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
                settings.AllowCharacter('\u2014');  // allow EM DASH through
                services.AddWebEncoders((options) =>
                {
                    options.TextEncoderSettings = settings;
                });
            }

            if (Scenarios.Any("Mvc"))
            {
                var mvcBuilder = services
                    .AddMvcCore()
                    //.AddApplicationPart(typeof(Startup).GetTypeInfo().Assembly)
                    .AddControllersAsServices();

                if (Scenarios.MvcJson || Scenarios.Any("MvcDbSingle") || Scenarios.Any("MvcDbMulti"))
                {
                    mvcBuilder.AddJsonFormatters();
                }

                if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes"))
                {
                    mvcBuilder
                        .AddViews()
                        .AddRazorViewEngine();
                }
            }
        }
开发者ID:nathana1,项目名称:FrameworkBenchmarks,代码行数:75,代码来源:Startup.cs

示例10: ConfigureServices

        // 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();
            services.AddSignalR();
            services.AddEntityFrameworkSqlServer(); // .AddEntityFramework().AddSqlServer();
            //services.AddDbContext<ProviderDbContext>(op => op.UseSqlServer(Configuration["Data:POC_DDDContextConnection"]));
            services.AddDbContext<ProviderDbContext>(op =>
                op.UseSqlServer(@"Data Source=.\SQL2016;Initial Catalog=POC_DDD;Integrated Security=False;User ID=srvelicheti;[email protected];MultipleActiveResultSets=true;Trusted_Connection=true;")
                );

            var container = new Container();

            // Here we populate the container using the service collection.
            // This will register all services from the collection
            // into the container with the appropriate lifetime.
            container.Populate(services);

            var bus = NServiceBusBootStrapper.Init(container);
            IocBootstrapper.ConfigureIocContainer(container,bus);
            // Make sure we return an IServiceProvider,
            // this makes Asp.Net Core use the StructureMap container.
            return container.GetInstance<IServiceProvider>();
        }
开发者ID:srivelicheti,项目名称:learning-DDD,代码行数:26,代码来源: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.AddApplicationInsightsTelemetry(Configuration);

            services.AddEntityFrameworkSqlServer();

            services.AddDbContext<ApplicationDbContext>(options =>
               options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

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

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }
开发者ID:gabrielbaptista,项目名称:GMQA,代码行数:21,代码来源: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.AddEntityFrameworkSqlServer()
             .AddDbContext<EfDbContext>((provider, options) =>
                  options.UseSqlServer(Configuration.GetValue<string>("ConnectionStringLocal"),
                                         b => b.MigrationsAssembly("Lab4"))
                  .UseInternalServiceProvider(provider));
     services.AddSingleton<IEnumerable<Bag>>(Bag.GetInitializedBags());
     // Add framework services.
     services.AddMvc();
 }
开发者ID:kostya9,项目名称:OP,代码行数:12,代码来源:Startup.cs

示例13: AddProviderServices

 public override IServiceCollection AddProviderServices(IServiceCollection services)
     => services.AddEntityFrameworkSqlServer();
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:2,代码来源:SqlServerTestHelpers.cs


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