本文整理汇总了C#中ServiceCollection.BuildServiceProvider方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.BuildServiceProvider方法的具体用法?C# ServiceCollection.BuildServiceProvider怎么用?C# ServiceCollection.BuildServiceProvider使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.BuildServiceProvider方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConfigureCloudFoundryOptions_With_VCAP_APPLICATION_Environment_NotPresent
public void ConfigureCloudFoundryOptions_With_VCAP_APPLICATION_Environment_NotPresent()
{
// Arrange
Environment.SetEnvironmentVariable("VCAP_APPLICATION", null);
var services = new ServiceCollection().AddOptions();
// Act and Assert
var builder = new ConfigurationBuilder().AddCloudFoundry();
var config = builder.Build();
services.Configure<CloudFoundryApplicationOptions>(config);
var service = services.BuildServiceProvider().GetService<IOptions<CloudFoundryApplicationOptions>>();
Assert.NotNull(service);
var options = service.Value;
Assert.Null(options.ApplicationId);
Assert.Null(options.ApplicationName);
Assert.Null(options.ApplicationUris);
Assert.Null(options.ApplicationVersion);
Assert.Null(options.InstanceId);
Assert.Null(options.Name);
Assert.Null(options.SpaceId);
Assert.Null(options.SpaceName);
Assert.Null(options.Start);
Assert.Null(options.Uris);
Assert.Equal(-1, options.DiskLimit);
Assert.Equal(-1, options.FileDescriptorLimit);
Assert.Equal(-1, options.InstanceIndex);
Assert.Equal(-1, options.MemoryLimit);
Assert.Equal(-1, options.Port);
}
示例2: ConfigureConfigServerClientSettingsOptions_WithDefaults
public void ConfigureConfigServerClientSettingsOptions_WithDefaults()
{
// Arrange
var services = new ServiceCollection().AddOptions();
var environment = new HostingEnvironment();
// Act and Assert
var builder = new ConfigurationBuilder().AddConfigServer(environment);
var config = builder.Build();
services.Configure<ConfigServerClientSettingsOptions>(config);
var service = services.BuildServiceProvider().GetService<IOptions<ConfigServerClientSettingsOptions>>();
Assert.NotNull(service);
var options = service.Value;
Assert.NotNull(options);
ConfigServerTestHelpers.VerifyDefaults(options.Settings);
Assert.Equal(ConfigServerClientSettings.DEFAULT_PROVIDER_ENABLED, options.Enabled);
Assert.Equal(ConfigServerClientSettings.DEFAULT_FAILFAST, options.FailFast);
Assert.Equal(ConfigServerClientSettings.DEFAULT_URI, options.Uri);
Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, options.Environment);
Assert.Equal(ConfigServerClientSettings.DEFAULT_CERTIFICATE_VALIDATION, options.ValidateCertificates);
Assert.Null(options.Name);
Assert.Null(options.Label);
Assert.Null(options.Username);
Assert.Null(options.Password);
}
示例3: TestBase
public TestBase()
{
if (ServiceProvider == null)
{
var services = new ServiceCollection();
// set up empty in-memory test db
services
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));
// add identity service
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AllReadyContext>();
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
// set up service provider for tests
ServiceProvider = services.BuildServiceProvider();
}
}
示例4: RemoveShouldRemoveServiceByGenericAndImplementation
public void RemoveShouldRemoveServiceByGenericAndImplementation()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<IInjectedService, InjectedService>();
serviceCollection.AddSingleton<IInjectedService, ReplaceableInjectedService>();
Assert.NotNull(serviceCollection.BuildServiceProvider().GetService<IInjectedService>());
serviceCollection.Remove<IInjectedService, ReplaceableInjectedService>();
Assert.IsAssignableFrom<InjectedService>(serviceCollection.BuildServiceProvider().GetService<IInjectedService>());
}
示例5: RemoveShouldRemoveServiceByGenericOnlyInterface
public void RemoveShouldRemoveServiceByGenericOnlyInterface()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<IInjectedService, InjectedService>();
serviceCollection.AddSingleton<IInjectedService, ReplaceableInjectedService>();
Assert.NotNull(serviceCollection.BuildServiceProvider().GetService<IInjectedService>());
serviceCollection.Remove<IInjectedService>();
Assert.Null(serviceCollection.BuildServiceProvider().GetService<IInjectedService>());
}
示例6: Main
public static void Main(string[] args)
{
// serilog provider configuration
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.ColoredConsole()
.CreateLogger();
// logger factory for program.cs - startup case
var log = new LoggerFactory().AddSerilog().CreateLogger(typeof(Program).FullName);
log.LogInformation("Starting from console launcher... press enter to stop.");
// load config
var config = new ConfigurationBuilder()
.AddJsonFile("analyserconf.json")
.Build();
// use microsofts built in simple DI container.
var services = new ServiceCollection();
configureServices(services, config);
var sp = services.BuildServiceProvider();
IDictionary<uint, AircraftBeaconSpeedAndTrack> beaconDisplayBuffer = null;
var events = new Dictionary<string, List<AircraftTrackEvent>>();
// disposable pattern to stop on read-line.
using (var analyser = sp.GetService<Core.OGNAnalyser>())
{
attachConsoleDisplay(beaconDisplayBuffer, events, analyser);
Console.ReadLine();
}
}
示例7: AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders
public void AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders()
{
// Arrange
var serviceCollection = new ServiceCollection();
// Act
serviceCollection.AddSingleton<IHtmlEncoder, CommonTestEncoder>();
serviceCollection.AddSingleton<IJavaScriptStringEncoder, CommonTestEncoder>();
// we don't register an existing URL encoder
serviceCollection.AddWebEncoders(options =>
{
options.CodePointFilter = new CodePointFilter().AllowChars("ace"); // only these three chars are allowed
});
// Assert
var serviceProvider = serviceCollection.BuildServiceProvider();
var htmlEncoder = serviceProvider.GetHtmlEncoder();
Assert.Equal("HtmlEncode[[abcde]]", htmlEncoder.HtmlEncode("abcde"));
var javaScriptStringEncoder = serviceProvider.GetJavaScriptStringEncoder();
Assert.Equal("JavaScriptStringEncode[[abcde]]", javaScriptStringEncoder.JavaScriptStringEncode("abcde"));
var urlEncoder = serviceProvider.GetUrlEncoder();
Assert.Equal("a%62c%64e", urlEncoder.UrlEncode("abcde"));
}
示例8: Activate_InitializesTagHelpers
public void Activate_InitializesTagHelpers(string name, int number)
{
// Arrange
var services = new ServiceCollection();
var builder = new MvcCoreBuilder(services);
builder.InitializeTagHelper<TestTagHelper>((h, vc) =>
{
h.Name = name;
h.Number = number;
h.ViewDataValue = vc.ViewData["TestData"];
});
var httpContext = MakeHttpContext(services.BuildServiceProvider());
var viewContext = MakeViewContext(httpContext);
var viewDataValue = new object();
viewContext.ViewData.Add("TestData", viewDataValue);
var activator = new DefaultTagHelperActivator();
var helper = new TestTagHelper();
// Act
activator.Activate(helper, viewContext);
// Assert
Assert.Equal(name, helper.Name);
Assert.Equal(number, helper.Number);
Assert.Same(viewDataValue, helper.ViewDataValue);
}
示例9: ConfigureStartup
internal static IServiceProvider ConfigureStartup(string startupTypeName, Action<IServiceCollection, bool> registerSystemTypes)
{
var usingCustomServiceProvider = false;
IServiceCollection serviceCollection = new ServiceCollection();
ConfigureServicesBuilder servicesMethod = null;
Type startupType = null;
if (!string.IsNullOrWhiteSpace(startupTypeName))
{
startupType = Type.GetType(startupTypeName);
if (startupType == null)
{
throw new InvalidOperationException($"Can not locate the type specified in the configuration file: '{startupTypeName}'.");
}
servicesMethod = FindConfigureServicesDelegate(startupType);
if (servicesMethod != null && !servicesMethod.MethodInfo.IsStatic)
{
usingCustomServiceProvider = true;
}
}
registerSystemTypes(serviceCollection, usingCustomServiceProvider);
if (usingCustomServiceProvider)
{
var instance = Activator.CreateInstance(startupType);
return servicesMethod.Build(instance, serviceCollection);
}
return serviceCollection.BuildServiceProvider();
}
示例10: CreateNewKey_CallsInternalManager
public void CreateNewKey_CallsInternalManager()
{
// Arrange - mocks
DateTimeOffset minCreationDate = DateTimeOffset.UtcNow;
DateTimeOffset? actualCreationDate = null;
DateTimeOffset activationDate = minCreationDate + TimeSpan.FromDays(7);
DateTimeOffset expirationDate = activationDate.AddMonths(1);
var mockInternalKeyManager = new Mock<IInternalXmlKeyManager>();
mockInternalKeyManager
.Setup(o => o.CreateNewKey(It.IsAny<Guid>(), It.IsAny<DateTimeOffset>(), activationDate, expirationDate))
.Callback<Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset>((innerKeyId, innerCreationDate, innerActivationDate, innerExpirationDate) =>
{
actualCreationDate = innerCreationDate;
});
// Arrange - services
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IXmlRepository>(new Mock<IXmlRepository>().Object);
serviceCollection.AddSingleton<IAuthenticatedEncryptorConfiguration>(new Mock<IAuthenticatedEncryptorConfiguration>().Object);
serviceCollection.AddSingleton<IInternalXmlKeyManager>(mockInternalKeyManager.Object);
var services = serviceCollection.BuildServiceProvider();
var keyManager = new XmlKeyManager(services);
// Act
keyManager.CreateNewKey(activationDate, expirationDate);
// Assert
Assert.InRange(actualCreationDate.Value, minCreationDate, DateTimeOffset.UtcNow);
}
示例11: GetBindingContext
private static DefaultModelBindingContext GetBindingContext(Type modelType)
{
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services);
var modelMetadata = metadataProvider.GetMetadataForType(modelType);
var services = new ServiceCollection();
services.AddSingleton<IService>(new Service());
var bindingContext = new DefaultModelBindingContext
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = services.BuildServiceProvider(),
}
},
ModelMetadata = modelMetadata,
ModelName = "modelName",
FieldName = "modelName",
ModelState = new ModelStateDictionary(),
BinderModelName = modelMetadata.BinderModelName,
BindingSource = modelMetadata.BindingSource,
ValidationState = new ValidationStateDictionary(),
};
return bindingContext;
}
示例12: ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName
public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
{
// Arrange
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty");
var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null);
var serviceCollection = new ServiceCollection();
var requestServices = serviceCollection.BuildServiceProvider();
var context = new ClientModelValidationContext(metadata, metadataProvider, requestServices);
// Act
var rules = adapter.GetClientValidationRules(context);
// Assert
var rule = Assert.Single(rules);
// Mono issue - https://github.com/aspnet/External/issues/19
Assert.Equal(
PlatformNormalizer.NormalizeContent(
"'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match."),
rule.ErrorMessage);
}
示例13: AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders
public void AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders()
{
// Arrange
var serviceCollection = new ServiceCollection();
// Act
serviceCollection.AddSingleton<HtmlEncoder, HtmlTestEncoder>();
serviceCollection.AddSingleton<JavaScriptEncoder, JavaScriptTestEncoder>();
// we don't register an existing URL encoder
serviceCollection.AddWebEncoders(options =>
{
options.TextEncoderSettings = new TextEncoderSettings();
options.TextEncoderSettings.AllowCharacters("ace".ToCharArray()); // only these three chars are allowed
});
// Assert
var serviceProvider = serviceCollection.BuildServiceProvider();
var htmlEncoder = serviceProvider.GetRequiredService<HtmlEncoder>();
Assert.Equal("HtmlEncode[[abcde]]", htmlEncoder.Encode("abcde"));
var javaScriptEncoder = serviceProvider.GetRequiredService<JavaScriptEncoder>();
Assert.Equal("JavaScriptEncode[[abcde]]", javaScriptEncoder.Encode("abcde"));
var urlEncoder = serviceProvider.GetRequiredService<UrlEncoder>();
Assert.Equal("a%62c%64e", urlEncoder.Encode("abcde"));
}
示例14: ManageControllerTest
public ManageControllerTest()
{
var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();
var services = new ServiceCollection();
services.AddOptions();
services
.AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MusicStoreContext>();
services.AddLogging();
services.AddOptions();
// IHttpContextAccessor is required for SignInManager, and UserManager
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = new TestAuthHandler() });
services.AddSingleton<IHttpContextAccessor>(
new HttpContextAccessor()
{
HttpContext = context,
});
_serviceProvider = services.BuildServiceProvider();
}
示例15: AreaViewLocationFormats_ContainsExpectedLocations
public void AreaViewLocationFormats_ContainsExpectedLocations()
{
// Arrange
var services = new ServiceCollection().AddOptions();
var areaViewLocations = new[]
{
"/Areas/{2}/MvcViews/{1}/{0}.cshtml",
"/Areas/{2}/MvcViews/Shared/{0}.cshtml",
"/MvcViews/Shared/{0}.cshtml"
};
var builder = new MvcBuilder(services, new ApplicationPartManager());
builder.AddRazorOptions(options =>
{
options.AreaViewLocationFormats.Clear();
foreach (var location in areaViewLocations)
{
options.AreaViewLocationFormats.Add(location);
}
});
var serviceProvider = services.BuildServiceProvider();
var accessor = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>();
// Act
var formats = accessor.Value.AreaViewLocationFormats;
// Assert
Assert.Equal(areaViewLocations, formats, StringComparer.Ordinal);
}