DependencyInjectionExtensions

We found 10 examples in language CSharp for this search. You will see 23 fragments of code.
        public static void AddTripModule(this IServiceCollection services)
        {
            services.AddTransient<ITripRepository, TripRepository>();

            services.AddAutoMapper(typeof(DependencyInjectionExtensions).Assembly);
            services.AddMediatR(typeof(DependencyInjectionExtensions).Assembly);
            services.AddValidatorsFromAssembly(typeof(DependencyInjectionExtensions).Assembly);
        }

        public static void AddApi(this IServiceCollection services)
        {
            services
                .AddMvcCore()
                .AddApplicationPart(typeof(DependencyInjectionExtensions).Assembly);
        }

using core;
using core.profanity;
using core.services;
using core.services.searchs;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;


var builder = WebApplication.CreateBuilder(args);

builder.WebHost
    .UseUrls($"http://*.*.*.*:{Environment.GetEnvironmentVariable("PORT") ?? "8080"}");
builder.WebHost.UseSentry(o =>
{
    o.Dsn = Environment.GetEnvironmentVariable("VEIN_SENTRY_DNS") ?? "";
    o.TracesSampleRate = 1.0;
    o.IsGlobalModeEnabled = Environment.GetEnvironmentVariable("VEIN_SENTRY_DNS") is not null;
});

builder.Services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<IStorageService>);
builder.Services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<IPackageService>);
builder.Services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<ISearchService>);
builder.Services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<ISearchIndexer>);

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.Authority = builder.Configuration["Auth0:Authority"];
    options.Audience = builder.Configuration["Auth0:Audience"];
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true
    };
});


builder.Services
    .AddControllers()
    .AddNewtonsoftJson(x =>
    {
        x.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        x.SerializerSettings.Formatting = Formatting.Indented;
        x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
builder.Services
    .AddRegistryApplication(x => { })
    .AddHttpContextAccessor()
    .AddHealthChecks();


builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "localhost",
        builder => builder.WithOrigins(
            "http://localhost:3000",
            "https://localhost:7181")
            .AllowAnyMethod()
            .AllowAnyHeader());
    options.AddPolicy(name: "production",
        builder => builder.WithOrigins(
            "https://api.vein.gallery",
            "https://vein.gallery")
            .AllowAnyHeader()
            .AllowAnyMethod());
});


var app = builder.Build();

app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseCors(app.Environment.IsDevelopment() ? "localhost" : "production");
app.UseAuthorization();
app.UseOperationCancelledMiddleware();
app.UseForwardedHeaders();
app.UseHttpsRedirection();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
    endpoints.MapControllers();
});

app.Run();

        [Test]
        public void DecoratedAndHostedTest()
        {
            GivenServiceCollectionExtensionWithDecoratorAndHosted();
            WhenAddService();
            ThenServiceDecoratedAndHostedAdded();
        }

        [Test]
        public void ImplementationAndHostedTest()
        {
            GivenServiceCollectionExtensionWithImplementationAndHosted();
            WhenAddService();
            ThenServiceImplementationAddedAndHostedAdded();
        }

        [Test]
        public void DecoratedAndImplementationTest()
        {
            GivenServiceCollectionExtensionWithDecoratorAndImplementation();
            WhenAddService();
            ThenServiceDecoratedAndImplementationAdded();
        }

        [Test]
        public void DecoratedImplementationAndHostedTest()
        {
            GivenServiceCollectionExtensionWithDecoratorImplementationAndHosted();
            WhenAddService();
            ThenServiceDecoratedImplementationAddedAndHostedAdded();
        }

        private void GivenServiceCollectionExtensionWithDecoratorAndHosted()
        {
            CreateServiceCollection(new IServiceCollectionExtension[]
            {
                new HostedServiceExtension(),
                new DecoratorExtension(new DecoratorOneFactory())
            });
        }

        private void GivenServiceCollectionExtensionWithImplementationAndHosted()
        {
            CreateServiceCollection(new IServiceCollectionExtension[]
            {
                new HostedServiceExtension(),
                new NotTransientImplementationExtension()
            });
        }

        public static IServiceCollection AddTransient<TInterface, TImplementation>(this IServiceCollection services, string named)
            where TInterface : class
            where TImplementation : class, TInterface
        {
            services.TryAddSingleton<INamedInstanceFactory<TInterface>, NamedInstanceFactory<TInterface>>();
            services.AddTransient<TImplementation>();
            var selector = new NamedInstanceSelector<TInterface>(named, typeof(TImplementation));
            services.AddTransient<INamedInstanceSelector<TInterface>>(_ => selector);
            return services;
        }
        
        public static IServiceCollection AddTransient<TInterface>(this IServiceCollection services, Type implementationType, string named)
            where TInterface : class
        {
            services.TryAddSingleton<INamedInstanceFactory<TInterface>, NamedInstanceFactory<TInterface>>();
            services.AddTransient(implementationType);
            var selector = new NamedInstanceSelector<TInterface>(named, implementationType);
            services.AddTransient<INamedInstanceSelector<TInterface>>(_ => selector);
            return services;
        }

        public static TInterface GetRequiredService<TInterface>(this IServiceProvider serviceProvider, string name)
            where TInterface : class
        {
            var namedFactory = serviceProvider.GetRequiredService<INamedInstanceFactory<TInterface>>();
            return namedFactory.Resolve(name);
        }
        
        public static TInterface GetRequiredService<TInterface>(this IServiceProvider serviceProvider, object parameter)
            where TInterface : class
        {
            var namedFactory = serviceProvider.GetRequiredService<ITypedInstanceFactory<TInterface>>();
            return namedFactory.Resolve(parameter.GetType(), parameter);
        }
        
        public static object GetRequiredService(this IServiceProvider serviceProvider, Type serviceType, string name)
        {
            var namedInstanceFactoryType = (typeof(INamedInstanceFactory<>)).MakeGenericType(serviceType);
            var namedFactory = (INamedInstanceFactory)serviceProvider.GetRequiredService(namedInstanceFactoryType);
            return namedFactory.Resolve(name);
        }
        
        public static IServiceCollection AddTransient<TInterface, TImplementation>(this IServiceCollection services, Type triggerType, Func<object, object[]> getArgs)
            where TInterface : class
            where TImplementation : class, TInterface
        {
            services.TryAddSingleton<ITypedInstanceFactory<TInterface>, TypedInstanceFactory<TInterface>>();
            services.AddTransient<TImplementation>();
            var selector = new TypedInstanceSelector<TInterface>( typeof(TImplementation), triggerType, getArgs);
            services.AddTransient<ITypedInstanceSelector<TInterface>>(_ => selector);
            return services;
        }


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddBaGetOptions<IISServerOptions>(nameof(IISServerOptions));

            // TODO: Ideally we'd use:
            //
            //       services.ConfigureOptions<ConfigureBaGetOptions>();
            //
            //       However, "ConfigureOptions" doesn't register validations as expected.
            //       We'll instead register all these configurations manually.
            // See: https://github.com/dotnet/runtime/issues/38491
            services.AddTransient<IConfigureOptions<CorsOptions>, ConfigureBaGetOptions>();
            services.AddTransient<IConfigureOptions<FormOptions>, ConfigureBaGetOptions>();
            services.AddTransient<IConfigureOptions<ForwardedHeadersOptions>, ConfigureBaGetOptions>();
            services.AddTransient<IConfigureOptions<IISServerOptions>, ConfigureBaGetOptions>();
            services.AddTransient<IValidateOptions<BaGetOptions>, ConfigureBaGetOptions>();

            services.AddSpaStaticFiles(ConfigureSpaStaticFiles);
            services.AddBaGetWebApplication(ConfigureBaGetApplication);

            // You can swap between implementations of subsystems like storage and search using BaGet's configuration.
            // Each subsystem's implementation has a provider that reads the configuration to determine if it should be
            // activated. BaGet will run through all its providers until it finds one that is active.
            services.AddScoped(DependencyInjectionExtensions.GetServiceFromProviders<IContext>);
            services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<IStorageService>);
            services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<IPackageService>);
            services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<ISearchService>);
            services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders<ISearchIndexer>);

            services.AddCors();
        }

        private void ConfigureSpaStaticFiles(SpaStaticFilesOptions options)
        {
            // In production, the UI files will be served from this directory
            options.RootPath = "BaGet.UI/build";
        }

        private void ConfigureBaGetApplication(BaGetApplication app)
        {
            // Add database providers.
            app.AddAzureTableDatabase();
            //app.AddMySqlDatabase();
            //app.AddPostgreSqlDatabase();
            //app.AddSqliteDatabase();
            //app.AddSqlServerDatabase();

            // Add storage providers.
            app.AddFileStorage();
            //app.AddAliyunOssStorage();
            //app.AddAwsS3Storage();
            app.AddAzureBlobStorage();
            app.AddGoogleCloudStorage();

            // Add search providers.
            app.AddAzureSearch();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var options = Configuration.Get<BaGetOptions>();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseStatusCodePages();
            }

            app.UseForwardedHeaders();
            app.UsePathBase(options.PathBase);

            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseCors(ConfigureBaGetOptions.CorsPolicy);
            app.UseOperationCancelledMiddleware();

            app.UseEndpoints(endpoints =>
            {
                var api = new BaGetApi();

                api.MapRoutes(endpoints);
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "../BaGet.UI";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }

        [Fact]
        public void T1()
        {
            var serviceProvider = ConfigureProvider(services =>
            {
                services.AddTransient<IFoo, BooFoo>();
                services.Decorate<IFoo, FooDecorator>();
            });

            var instance = serviceProvider.GetRequiredService<IFoo>();

            instance.Should().BeOfType<FooDecorator>();
            ((FooDecorator) instance).Inner.Should().BeOfType<BooFoo>();
        }

        public static IServiceCollection UseServices(this IServiceCollection services)
        {
            services.AddAutoMapper(typeof(AutoMapperProfile));
            services.AddScoped<IUnitOfWork, UnitOfWork>();
            foreach (var x in typeof(UnitOfWork).Assembly.GetTypes().Where(x => !x.IsInterface && x.Namespace.StartsWith("Jt808TerminalEmulator.Repository.Repositorys")).Select(x => new { Implementation = x, Services = x.GetInterfaces() }))
            {
                foreach (var service in x.Services)
                {
                    services.AddScoped(service, x.Implementation);
                }
            };
            //通过反射,批量取出需要注入的接口和实现类
            foreach (var x in typeof(DependencyInjectionExtensions).Assembly.GetTypes().Where(x => x.Namespace != null && x.Namespace.StartsWith("Jt808TerminalEmulator.Servic") && x.GetInterfaces().Any(x => x.Name.EndsWith("Service"))).Select(x => new { Implementation = x, Services = x.GetInterfaces() }))
            {
                foreach (var service in x.Services)
                {
                    services.AddScoped(service, x.Implementation);
                }
            }
            return services;
        }

        public static void AddScoped<Interface1, Interface2, TImplementation>(this IServiceCollection services)
          where Interface1 : class
          where Interface2 : class
          where TImplementation : class, Interface1, Interface2
        {
            services.AddScoped<Interface1, TImplementation>();
            services.AddScoped<Interface2, TImplementation>(x => (TImplementation)x.GetService<Interface1>());
        }

        public static IServiceCollection AddApplicationServices(this IServiceCollection services) =>
            services.AddMediatR(typeof(DependencyInjectionExtensions).Assembly);

FluentValidation.DependencyInjectionExtensions : Object

Methods :

public static IServiceProvider GetServiceProvider(IValidationContext context = )
public static IServiceProvider GetServiceProvider(MessageBuilderContext<T, TProperty> context = )
public static Void SetServiceProvider(IValidationContext context = , IServiceProvider serviceProvider = )
public static IRuleBuilderOptions<T, TProperty> InjectValidator(IRuleBuilder<T, TProperty> ruleBuilder = , String[] ruleSets = )
public static IRuleBuilderOptions<T, TProperty> InjectValidator(IRuleBuilder<T, TProperty> ruleBuilder = , Func<IServiceProvider, ValidationContext<T>, IValidator<TProperty>> callback = , String[] ruleSets = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods