本文整理汇总了C#中IServiceProvider.GetRequiredService方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceProvider.GetRequiredService方法的具体用法?C# IServiceProvider.GetRequiredService怎么用?C# IServiceProvider.GetRequiredService使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IServiceProvider
的用法示例。
在下文中一共展示了IServiceProvider.GetRequiredService方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateAdminUser
/// <summary>
/// Creates a store manager user who can manage the inventory.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private static async Task CreateAdminUser(IServiceProvider serviceProvider)
{
//var options = serviceProvider.GetRequiredService<IOptions<IdentityDbContextOptions>>().Value;
const string adminRole = "Administrator";
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var list = new List<string>() { "Administrator","Cobranças","Director de Area","Funcionario" };
foreach(var role in list)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}
//var user = await userManager.FindByNameAsync("[email protected]");
//if (user == null)
//{
// user = new ApplicationUser { UserName = "[email protected]" };
// await userManager.CreateAsync(user, "Accsys2011!");
// await userManager.AddToRoleAsync(user, adminRole);
// await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
//}
//else
//{
// //await userManager.AddToRoleAsync(user, adminRole);
// //await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
//}
}
示例2: AddOrchardLogging
public static ILoggerFactory AddOrchardLogging(
this ILoggerFactory loggingFactory,
IServiceProvider serviceProvider)
{
/* TODO (ngm): Abstract this logger stuff outta here! */
var loader = serviceProvider.GetRequiredService<IExtensionLoader>();
var manager = serviceProvider.GetRequiredService<IExtensionManager>();
var descriptor = manager.GetExtension("Orchard.Logging.Console");
var entry = loader.Load(descriptor);
var loggingInitiatorTypes = entry
.Assembly
.ExportedTypes
.Where(et => typeof(ILoggingInitiator).IsAssignableFrom(et));
IServiceCollection loggerCollection = new ServiceCollection();
foreach (var initiatorType in loggingInitiatorTypes) {
loggerCollection.AddScoped(typeof(ILoggingInitiator), initiatorType);
}
var moduleServiceProvider = serviceProvider.CreateChildContainer(loggerCollection).BuildServiceProvider();
foreach (var service in moduleServiceProvider.GetServices<ILoggingInitiator>()) {
service.Initialize(loggingFactory);
}
return loggingFactory;
}
示例3: CreateAttributeMegaRoute
/// <summary>
/// Creates an attribute route using the provided services and provided target router.
/// </summary>
/// <param name="target">The router to invoke when a route entry matches.</param>
/// <param name="services">The application services.</param>
/// <returns>An attribute route.</returns>
public static IRouter CreateAttributeMegaRoute(IRouter target, IServiceProvider services)
{
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var actionDescriptorProvider = services.GetRequiredService<IActionDescriptorCollectionProvider>();
var inlineConstraintResolver = services.GetRequiredService<IInlineConstraintResolver>();
var pool = services.GetRequiredService<ObjectPool<UriBuildingContext>>();
var urlEncoder = services.GetRequiredService<UrlEncoder>();
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
return new AttributeRoute(
target,
actionDescriptorProvider,
inlineConstraintResolver,
pool,
urlEncoder,
loggerFactory);
}
示例4: InitDB
public async static Task InitDB(IServiceProvider service)
{
var db = service.GetRequiredService<ForumContext>();
var userManager = service.GetRequiredService<UserManager<User>>();
var roleManager = service.GetRequiredService<RoleManager<IdentityRole>>();
if (db.Database != null && db.Database.EnsureCreated())
{
await roleManager.CreateAsync(new IdentityRole { Name = "网站站长" });
await roleManager.CreateAsync(new IdentityRole { Name = "网站管理员" });
await roleManager.CreateAsync(new IdentityRole { Name = "普通用户" });
var user = new User { UserName = "Admin" ,Name="付东东",Question="我最喜欢的编程语言",Answer="C#",NewsCount=0,AriticleCount=0,PostedCount=0};
await userManager.CreateAsync(user, "[email protected]#");
await userManager.AddToRoleAsync(user, "网站站长");
var user1 = new User { UserName = "Guest" ,Name = "付东东" , Question = "我最喜欢的编程语言", Answer = "C#" , NewsCount = 0, AriticleCount = 0, PostedCount = 0 };
await userManager.CreateAsync(user1, "[email protected]#");
await userManager.AddToRoleAsync(user1, "网站管理员");
var user2 = new User { UserName = "Cream2015" ,Name = "付东东", Question = "我最喜欢的编程语言", Answer = "C#", NewsCount = 0, AriticleCount = 0, PostedCount = 0 };
await userManager.CreateAsync(user2, "[email protected]#");
await userManager.AddToRoleAsync(user2, "普通用户");
}
db.SaveChanges();
}
示例5: SeedAdminUsersAsync
private static async Task SeedAdminUsersAsync(IServiceProvider serviceProvider)
{
const string adminUserEmail = "[email protected]";
const string roleName = "Administrator";
var userManager = serviceProvider.GetRequiredService<UserManager<AdminUser>>();
var roleManager = serviceProvider.GetRequiredService<RoleManager<AdminRole>>();
if (!await roleManager.RoleExistsAsync(roleName))
{
var adminRole = new AdminRole(roleName);
await roleManager.CreateAsync(adminRole);
await roleManager.AddClaimAsync(adminRole, new Claim("ManageRole", "Allowed"));
}
var user = await userManager.FindByEmailAsync(adminUserEmail);
if (user == null)
{
user = new AdminUser { UserName = adminUserEmail, Email = adminUserEmail };
await userManager.CreateAsync(user, "!QAZ2wsx");
await userManager.AddToRoleAsync(user, roleName);
await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
}
}
示例6: CreateSwaggerProvider
private static ISwaggerProvider CreateSwaggerProvider(IServiceProvider serviceProvider)
{
var optionsAccessor = serviceProvider.GetService<IOptions<SwaggerDocumentOptions>>();
return new DefaultSwaggerProvider(
serviceProvider.GetRequiredService<IApiDescriptionGroupCollectionProvider>(),
serviceProvider.GetRequiredService<ISchemaRegistryFactory>(),
optionsAccessor.Value);
}
示例7: InitDB
public async static Task InitDB(IServiceProvider services)
{
var DB = services.GetRequiredService<DaoliContext>();
var UserManager = services.GetRequiredService<UserManager<User>>();
if (DB.Database != null && DB.Database.EnsureCreated())
{
var user = new User { UserName = "admin" };
await UserManager.CreateAsync(user, "123456");
}
}
示例8: InitDB
public static async void InitDB(IServiceProvider services)
{
var DB = services.GetRequiredService<JsonAntiXssContext>();
var RoleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = services.GetRequiredService<UserManager<IdentityUser>>();
await RoleManager.CreateAsync(new IdentityRole("Root"));
var user = new IdentityUser { Id = "00000000-0000-0000-0000-000000000000", UserName = "admin" };
await UserManager.CreateAsync(user, "123456");
await UserManager.AddToRoleAsync(user, "Root");
}
示例9: Navigator
internal Navigator([NotNull] IServiceProvider serviceProvider)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
_serviceProvider = serviceProvider;
_uiAsyncOperation = _serviceProvider.GetRequiredService<IUIShell>().CreateUIAsyncOperation();
_form = new NavigationDummyForm(_serviceProvider);
_serviceProvider.GetRequiredService<DockManager>().RegisterPersistablePane(_form);
}
示例10: BuildSampleData
private async void BuildSampleData(IServiceProvider service)
{
service.GetRequiredService<IInMemoryStore>().Clear();
var db = service.GetRequiredService<ApplicationDbContext>();
if (db.Database != null && db.Database.EnsureCreated())
{
var userManager = service.GetService<UserManager<ApplicationUser>>();
var roleManager = service.GetService<RoleManager<IdentityRole>>();
await CreateUserIfNotExist(userManager, "[email protected]", "@password!", Roles.Admin.ToString());
}
}
示例11: AddDefaultServices
public static IServiceCollection AddDefaultServices(this IServiceCollection services, IServiceProvider defaultProvider)
{
var runtimeServices = defaultProvider.GetRequiredService<IRuntimeServices>();
foreach (var service in runtimeServices.Services)
{
services.AddInstance(service, defaultProvider.GetRequiredService(service));
}
services.AddInstance(runtimeServices);
return services;
}
示例12: InitDB
public async static Task InitDB(IServiceProvider service)
{
//获取上下文实例
var db = service.GetRequiredService<StudentContext>();
//获取UserManager实例
var userManager = service.GetRequiredService<UserManager<User>>();
if(db.Database!=null&&db.Database.EnsureCreated())
{
//创建初始用户
await userManager.CreateAsync(new User
{
UserName = "admin",
Email = "[email protected]"
}, "[email protected]#");
//创建初始个人信息,int型ID会根据seed自动递增
db.Students.Add(new Student
{
Name = "Cream",
Sex = "M",
Age = 20,
Class = "软件121",
Address = "地球村",
Note="无",
Phone=18888888888,
});
db.Students.Add(new Student
{
Name = "CXS",
Sex = "W",
Age = 25,
Class = "软件122",
Address = "克山火车站旁边小卖部",
Note = "无",
Phone=13333333333,
});
db.Students.Add(new Student
{
Name = "YYP",
Sex = "M",
Age = 30,
Class = "软件123",
Address = "大连华信软件公司",
Note = "无",
Phone=13777777777,
});
db.SaveChanges();
}
}
示例13: InitDB
public static void InitDB(IServiceProvider services)
{
var DB = services.GetRequiredService<TimedJobSiteContext>();
var TimedJobService = services.GetRequiredService<TimedJobService>();
DB.Database.EnsureCreated();
DB.TimedJobs.Add(new Pomelo.AspNetCore.TimedJob.EntityFramework.TimedJob
{
Id = "TimedJobSite.Jobs.GarbageCollectJob.Print",
Begin = DateTime.Now,
Interval = 3000,
IsEnabled = true
});
DB.SaveChanges();
TimedJobService.RestartDynamicTimers();
}
示例14: InitializeDatabase
public static async Task InitializeDatabase(IServiceProvider serviceProvider)
{
try
{
using (var db = serviceProvider.GetService<CTContext>())
{
var sqlServerDatabase = db.Database;
if (sqlServerDatabase != null)
{
if (await sqlServerDatabase.EnsureCreatedAsync())
{
var userManager = serviceProvider.GetRequiredService<UserManager<User>>();
var result = await userManager.CreateAsync(new User
{
Email = "[email protected]",
UserName = "Admin"
}, "[email protected]#");
}
}
else
{
//
}
}
}
catch (Exception ex)
{
}
}
示例15: ConfigureAuthentication
public void ConfigureAuthentication(IApplicationBuilder app, IOptions<AzureAdSettings> azureADSettings, IServiceProvider serviceProvider)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AutomaticAuthenticate = true
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = AuthenticationConstants.OpenIdConnectAzureAdB2CAuthenticationScheme,
AutomaticChallenge = true,
ClientId = azureADSettings.Value.ClientId,
Authority = azureADSettings.Value.Authority,
ResponseType = OpenIdConnectResponseType.IdToken,
PostLogoutRedirectUri = azureADSettings.Value.PostLogoutRedirectUri,
Events = new OpenIdConnectEvents
{
OnAuthenticationFailed = OnAuthenticationFailed,
// OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,
OnRedirectToIdentityProviderForSignOut = OnRedirectToIdentityProviderForSignOut
},
// The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
// endpoints from the OpenID Connect metadata endpoint. It is included in the Authentication folder.
ConfigurationManager = serviceProvider.GetRequiredService<PolicyConfigurationManager>(),
SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme
});
}