本文整理汇总了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();
}
示例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();
}
}
}
示例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>();
}
示例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>();
}
示例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"])
// );
}
示例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>();
//
}
示例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>();
}
示例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")
//.........这里部分代码省略.........
示例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();
}
}
}
示例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>();
}
示例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>();
}
示例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();
}
示例13: AddProviderServices
public override IServiceCollection AddProviderServices(IServiceCollection services)
=> services.AddEntityFrameworkSqlServer();