public override ODataSerializer GetODataPayloadSerializer(Type type, HttpRequestMessage request) { if (typeof(IEdmModel).IsAssignableFrom(type)) { IServiceProvider oldProvider = request.Properties[RequestContainerKey] as IServiceProvider; IContainerBuilder builder = new DefaultContainerBuilder(); builder.AddDefaultODataServices(); builder.AddService <IEdmModel>(ServiceLifetime.Singleton, sp => CreateEdmModel()); builder.AddService <IODataPathHandler, DefaultODataPathHandler>(ServiceLifetime.Singleton); builder.AddServicePrototype(new ODataMessageWriterSettings { EnableMessageStreamDisposal = false, MessageQuotas = new ODataMessageQuotas { MaxReceivedMessageSize = Int64.MaxValue }, }); IServiceProvider serviceProvider = builder.BuildContainer(); request.Properties[RequestContainerKey] = serviceProvider; return(new MyMetadataSerializer(oldProvider)); } return(base.GetODataPayloadSerializer(type, request)); }
public void AddScopedService_Works() { IContainerBuilder builder = new DefaultContainerBuilder(); builder.AddService <ITestService, TestService>(ServiceLifetime.Scoped); IServiceProvider container = builder.BuildContainer(); IServiceProvider scopedContainer1 = container.GetRequiredService <IServiceScopeFactory>() .CreateScope().ServiceProvider; ITestService o11 = scopedContainer1.GetService <ITestService>(); ITestService o12 = scopedContainer1.GetService <ITestService>(); Assert.NotNull(o11); Assert.NotNull(o12); Assert.Equal(o11, o12); IServiceProvider scopedContainer2 = container.GetRequiredService <IServiceScopeFactory>() .CreateScope().ServiceProvider; ITestService o21 = scopedContainer2.GetService <ITestService>(); ITestService o22 = scopedContainer2.GetService <ITestService>(); Assert.NotNull(o21); Assert.NotNull(o22); Assert.Equal(o21, o22); Assert.NotEqual(o11, o21); }
/// <summary> /// Initializes a new instance of the <see cref="ODataConventionModelBuilder"/> class. /// </summary> /// <returns>A new instance of the <see cref="ODataConventionModelBuilder"/> class.</returns> public static ODataConventionModelBuilder Create() { // Create an application part manager with both the product and test assemblies. ApplicationPartManager applicationPartManager = new ApplicationPartManager(); applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(ODataConventionModelBuilder).Assembly)); // Make sure call Create() method from "Microsoft.Test.AspNet{Core}.OData" Assembly assembly = Assembly.GetCallingAssembly(); Debug.Assert(assembly.FullName.Contains("Microsoft.Test.AspNet.OData") || assembly.FullName.Contains("Microsoft.Test.AspNetCore.OData")); applicationPartManager.ApplicationParts.Add(new AssemblyPart(assembly)); // Also, a few tests are built on CultureInfo so include it as well. applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(CultureInfo).Assembly)); IContainerBuilder container = new DefaultContainerBuilder(); container.AddService(ServiceLifetime.Singleton, sp => applicationPartManager); IServiceProvider serviceProvider = container.BuildContainer(); return(new ODataConventionModelBuilder(serviceProvider)); }
// Creates a mock of an ODataModelBuilder or any subclass of it that disables model validation // in order to reduce verbosity on tests. public static T GetModelBuilderMock <T>() where T : ODataModelBuilder { #if NETCORE Mock <T> mock; if (typeof(T) == typeof(ODataConventionModelBuilder)) { ApplicationPartManager applicationPartManager = new ApplicationPartManager(); AssemblyPart part = new AssemblyPart(typeof(ODataModelBuilderMocks).Assembly); applicationPartManager.ApplicationParts.Add(part); IContainerBuilder container = new DefaultContainerBuilder(); container.AddService(ServiceLifetime.Singleton, sp => applicationPartManager); IServiceProvider serviceProvider = container.BuildContainer(); mock = new Mock <T>(serviceProvider); } else { mock = new Mock <T>(); } #else Mock <T> mock = new Mock <T>(); #endif mock.Setup(b => b.ValidateModel(It.IsAny <IEdmModel>())).Callback(() => { }); mock.CallBase = true; return(mock.Object); }
private static IContainerBuilder CreateContainerBuilderWithDefaultServices(this HttpConfiguration configuration) { IContainerBuilder builder; object value; if (configuration.Properties.TryGetValue(ContainerBuilderFactoryKey, out value)) { Func <IContainerBuilder> builderFactory = (Func <IContainerBuilder>)value; builder = builderFactory(); if (builder == null) { throw Error.InvalidOperation(SRResources.NullContainerBuilder); } } else { builder = new DefaultContainerBuilder(); } builder.AddService(ServiceLifetime.Singleton, sp => configuration); builder.AddService(ServiceLifetime.Singleton, sp => configuration.GetDefaultQuerySettings()); builder.AddDefaultODataServices(); builder.AddDefaultWebApiServices(); return(builder); }
public VersionedMetadataRoutingConventionTest() { var builder = new DefaultContainerBuilder(); builder.AddDefaultODataServices(); builder.AddService(Singleton, typeof(IEdmModel), sp => Test.Model); serviceProvider = builder.BuildContainer(); }
public void AddService_WithImplementationFactory() { IContainerBuilder builder = new DefaultContainerBuilder(); builder.AddService <ITestService>(ServiceLifetime.Transient, sp => new TestService()); IServiceProvider container = builder.BuildContainer(); Assert.NotNull(container.GetService <ITestService>()); }
private void InitializeServices() { var containerBuilder = new DefaultContainerBuilder(); containerBuilder.AddService( Microsoft.OData.ServiceLifetime.Scoped, typeof(Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager), typeof(Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager)); containerBuilder.AddService( Microsoft.OData.ServiceLifetime.Scoped, typeof(ODataQuerySettings), sp => new ODataQuerySettings() { HandleNullPropagation = this.HandleNullPropagation ? HandleNullPropagationOption.True : HandleNullPropagationOption.False, }); containerBuilder.AddService( Microsoft.OData.ServiceLifetime.Scoped, typeof(IEdmModel), sp => { return(_model); }); containerBuilder.AddService( Microsoft.OData.ServiceLifetime.Scoped, typeof(Microsoft.OData.UriParser.ODataUriResolver), sp => { return(new Microsoft.OData.UriParser.ODataUriResolver() { }); }); containerBuilder.AddService( Microsoft.OData.ServiceLifetime.Scoped, typeof(Microsoft.OData.ODataSimplifiedOptions), sp => { return(new Microsoft.OData.ODataSimplifiedOptions() { }); }); containerBuilder.AddService( Microsoft.OData.ServiceLifetime.Scoped, typeof(Microsoft.OData.UriParser.ODataUriParserSettings), sp => { return(new Microsoft.OData.UriParser.ODataUriParserSettings() { }); }); _serviceProvider = containerBuilder.BuildContainer(); }
public void AddServiceWithImplementationFactory_ThrowsArgumentNull_ForInputParameters() { // Arrange & Act & Assert DefaultContainerBuilder builder = new DefaultContainerBuilder(); ExceptionAssert.ThrowsArgumentNull( () => builder.AddService(ServiceLifetime.Singleton, serviceType: null, implementationFactory: null), "serviceType"); ExceptionAssert.ThrowsArgumentNull( () => builder.AddService(ServiceLifetime.Singleton, serviceType: typeof(int), implementationFactory: null), "implementationFactory"); }
private static void RegisterDependencies(HttpConfiguration httpConfiguration, IConfigurationService configuration, Action <ContainerBuilder> register) { var builder = new ContainerBuilder(); DefaultContainerBuilder.Register(builder, configuration); SupportContainerBuilder.Register(builder, SupportEnvironment.WebApp); builder.RegisterType <NullPackageProcessor>() .As <IPackageProcessor>(); builder.RegisterType <DataController>(); builder.RegisterType <PackagesController>(); builder.RegisterWebApiFilterProvider(httpConfiguration); builder.RegisterType <AuthenticationFilter>() .WithParameter(TypedParameter.From <AuthenticatedAreaAttribute>(null)) .AsWebApiAuthenticationFilterFor <DataController>(); //var metadataAreaAttribute = new AuthenticatedAreaAttribute( // AuthenticatedArea.None, "feedName"); //builder.RegisterType<AuthenticationFilter>() // .WithParameter(TypedParameter.From(metadataAreaAttribute)) // .AsWebApiAuthenticationFilterFor<ODataMetadataController>(); var queryingAreaAttribute = new AuthenticatedAreaAttribute( AuthenticatedArea.Querying, "feedName"); builder.RegisterType <AuthenticationFilter>() .WithParameter(TypedParameter.From(queryingAreaAttribute)) .AsWebApiAuthenticationFilterFor <ODataController>(); builder.RegisterType <AuthenticationFilter>() .WithParameter(TypedParameter.From(queryingAreaAttribute)) .AsWebApiAuthenticationFilterFor <PackagesController>(); builder.RegisterType <AuthenticationNoneFilter>() .Keyed <IAutofacAuthenticationFilter>(AuthenticationMode.None); builder.RegisterType <AuthenticationBasicFilter>() .Keyed <IAutofacAuthenticationFilter>(AuthenticationMode.Basic); builder.RegisterType <AuthenticationNuGetApiKeyFilter>() .Keyed <IAutofacAuthenticationFilter>(AuthenticationMode.NuGetApiKey); register?.Invoke(builder); var container = builder.Build(); httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(container); }
public void AddService_WithImplementationType() { // Arrange IContainerBuilder builder = new DefaultContainerBuilder(); builder.AddService <ITestService, TestService>(ServiceLifetime.Transient); // Act IServiceProvider container = builder.BuildContainer(); // Assert Assert.NotNull(container.GetService <ITestService>()); }
public void AddSingletonService_Works() { IContainerBuilder builder = new DefaultContainerBuilder(); builder.AddService <ITestService, TestService>(ServiceLifetime.Singleton); IServiceProvider container = builder.BuildContainer(); ITestService o1 = container.GetService <ITestService>(); ITestService o2 = container.GetService <ITestService>(); Assert.NotNull(o1); Assert.Equal(o1, o2); }
public void AddTransientService_Works() { // Arrange IContainerBuilder builder = new DefaultContainerBuilder(); builder.AddService <ITestService, TestService>(ServiceLifetime.Transient); IServiceProvider container = builder.BuildContainer(); // Act ITestService o1 = container.GetService <ITestService>(); ITestService o2 = container.GetService <ITestService>(); // Assert Assert.NotNull(o1); Assert.NotNull(o2); Assert.NotEqual(o1, o2); }
protected override void OnStart(string[] args) { Trace.Listeners.Add(new ConsoleTraceListener()); foreach (var assembly in typeof(PackageProcessor).Assembly.GetReferencedAssemblies()) { Trace.WriteLine(assembly.FullName); } _stopSource = new CancellationTokenSource(); var configuration = new DefaultConfigurationService(); var builder = new ContainerBuilder(); DefaultContainerBuilder.Register(builder, configuration); SupportContainerBuilder.Register(builder, SupportEnvironment.WebJob); PackageProcessorContainerBuilder.Register(builder); var container = builder.Build(); var support = container.Resolve <ISupportConfiguration>(); var scheduler = container.Resolve <ISchedulerService>(); Task.Run(() => { int i = 0; while (!_stopSource.IsCancellationRequested) { try { scheduler.ListenAndProcess(_stopSource.Token); } catch { i++; if (i > 10) { Stop(); } } } }); }
static void Main(string[] args) { Trace.Listeners.Add(new ConsoleTraceListener()); foreach (var assembly in typeof(PackageProcessor).Assembly.GetReferencedAssemblies()) { Trace.WriteLine(assembly.FullName); } var cancelSource = new CancellationTokenSource(); System.Console.CancelKeyPress += (o, e) => { cancelSource.Cancel(); e.Cancel = true; }; var shutdownWatcher = new WebJobsShutdownWatcher(); var shutdownSource = CancellationTokenSource.CreateLinkedTokenSource(new[] { shutdownWatcher.Token, cancelSource.Token }); var configuration = new DefaultConfigurationService(); var builder = new ContainerBuilder(); DefaultContainerBuilder.Register(builder, configuration); SupportContainerBuilder.Register(builder, SupportEnvironment.WebJob); EmailContainerBuilder.Register(builder); PackageProcessorContainerBuilder.Register(builder); var container = builder.Build(); var support = container.Resolve <ISupportConfiguration>(); if (!string.IsNullOrWhiteSpace(support.InsightsInstrumentationKey)) { TelemetryConfiguration.Active.InstrumentationKey = support.InsightsInstrumentationKey; } var scheduler = container.Resolve <ISchedulerService>(); scheduler.ListenAndProcess(shutdownSource.Token); }
/// <summary> /// Initialize the ODataMigrationOutputFormatter and specify that it only accepts JSON UTF8/Unicode input /// </summary> /// <param name="payloadKinds">The types of payloads accepted by this output formatter.</param> public ODataMigrationOutputFormatter(IEnumerable <ODataPayloadKind> payloadKinds) : base(payloadKinds) { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json")); SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); // Use some of the injected services that are untouched by this extension, while leaving some out to override. IContainerBuilder builder = new DefaultContainerBuilder(); builder.AddService <ODataServiceDocumentSerializer, ODataServiceDocumentSerializer>(Microsoft.OData.ServiceLifetime.Scoped); builder.AddService <ODataEntityReferenceLinkSerializer, ODataEntityReferenceLinkSerializer> (Microsoft.OData.ServiceLifetime.Scoped); builder.AddService <ODataEntityReferenceLinksSerializer, ODataEntityReferenceLinksSerializer> (Microsoft.OData.ServiceLifetime.Scoped); builder.AddService <ODataErrorSerializer, ODataErrorSerializer>(Microsoft.OData.ServiceLifetime.Scoped); builder.AddService <ODataMetadataSerializer, ODataMetadataSerializer>(Microsoft.OData.ServiceLifetime.Scoped); builder.AddService <ODataRawValueSerializer, ODataRawValueSerializer>(Microsoft.OData.ServiceLifetime.Scoped); this.customContainer = builder.BuildContainer(); }
/// <summary> /// Initializes a new instance of the <see cref="ODataConventionModelBuilder"/> class. /// </summary> /// <returns>A new instance of the <see cref="ODataConventionModelBuilder"/> class.</returns> public static ODataConventionModelBuilder Create() { // Create an application part manager with both the product and test assemblies. ApplicationPartManager applicationPartManager = new ApplicationPartManager(); applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(ODataConventionModelBuilder).Assembly)); applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(ODataConventionModelBuilderFactory).Assembly)); // Also, a few tests are built on CultureInfo so include it as well. applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(CultureInfo).Assembly)); IContainerBuilder container = new DefaultContainerBuilder(); container.AddService(ServiceLifetime.Singleton, sp => applicationPartManager); IServiceProvider serviceProvider = container.BuildContainer(); return(new ODataConventionModelBuilder(serviceProvider)); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { IContainerBuilder containerBuilder = new DefaultContainerBuilder(); containerBuilder.Build(); ServiceRuntime.RegisterServiceAsync("DiscoveryServiceType", ServiceFactory).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(DiscoveryService).Name); // Prevents this host process from terminating so services keeps running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } }
private static IServiceProvider BuilderDefaultServiceProvider(Action <IContainerBuilder> setupAction) { IContainerBuilder odataContainerBuilder = new DefaultContainerBuilder(); odataContainerBuilder.AddDefaultODataServices(); odataContainerBuilder.AddService(ServiceLifetime.Singleton, sp => new DefaultQuerySettings()); odataContainerBuilder.AddService(ServiceLifetime.Singleton, typeof(ODataUriResolver), sp => new UnqualifiedODataUriResolver { EnableCaseInsensitive = true }); // Inject the default Web API OData services. odataContainerBuilder.AddDefaultWebApiServices(); // Inject the customized services. setupAction?.Invoke(odataContainerBuilder); return(odataContainerBuilder.BuildContainer()); }
public static void AddDefaultSerializers(IServiceCollection services, IODataSerializerProvider serializerProvider) { // This is necessary to query the IOption<ODataOptions> services.AddOptions(); // add the default OData lib services into service collection. IContainerBuilder builder = new DefaultContainerBuilder(services); builder.AddDefaultODataServices(); services.TryAddEnumerable(ServiceDescriptor.Transient <IConfigureOptions <ODataOptions>, ODataOptionsSetup>()); services.TryAdd(ServiceDescriptor.Singleton(s => new ODataEnumSerializer(serializerProvider))); services.TryAdd(ServiceDescriptor.Singleton(s => new ODataResourceSerializer(serializerProvider))); services.TryAdd(ServiceDescriptor.Singleton(s => new ODataResourceSetSerializer(serializerProvider))); services.AddSingleton <ODataPrimitiveSerializer>(); services.AddSingleton <ODataEntityReferenceLinkSerializer>(); services.AddSingleton <ODataEntityReferenceLinksSerializer>(); services.AddSingleton <ODataErrorSerializer>(); services.AddSingleton <ODataRawValueSerializer>(); }
/// <summary> /// Configures the dependency resolver for Cofoundry and /// registers all the services, repositories and modules setup for auto-registration. /// </summary> public static IMvcBuilder AddCofoundry( this IMvcBuilder mvcBuilder, IConfiguration configuration, Action <AddCofoundryStartupConfiguration> configBuilder = null ) { var cofoundryConfig = new AddCofoundryStartupConfiguration(); configBuilder?.Invoke(cofoundryConfig); AddAdditionalTypes(mvcBuilder); DiscoverAdditionalApplicationParts(mvcBuilder, cofoundryConfig); var typesProvider = new DiscoveredTypesProvider(mvcBuilder.PartManager); var builder = new DefaultContainerBuilder(mvcBuilder.Services, typesProvider, configuration); builder.Build(); RunAdditionalConfiguration(mvcBuilder); return(mvcBuilder); }