Skip to content

⚡Dependency Injection without type⌨️ fatigue✍️

License

Notifications You must be signed in to change notification settings

DrSensor/BatchDI

Repository files navigation

Batch Dependency Injection

version download

Status OS
Build status Windows
Build Status Linux, OS X

This package/library use for doing multiple dependency injection in easy way. For more info about DI (Dependency Injection) see here.

The real reason is I want to avoid this when using GraphQL

copas from this repo

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IOrderService, OrderService>();
        services.AddSingleton<OrdersSchema>();
        services.AddSingleton<OrdersQuery>();
        services.AddSingleton<OrderType>();
        services.AddSingleton<OrderCreateInputType>();
        services.AddSingleton<ICustomerService, CustomerService>();
        services.AddSingleton<CustomerType>();
        services.AddSingleton<OrderStatusesEnum>();
        services.AddSingleton<OrdersMutation>();
        services.AddSingleton<OrderSubscription>();
        services.AddSingleton<OrderEventType>();
        services.AddSingleton<IOrderEventService, OrderEventService>();
        services.AddSingleton<IEventAggregator, SimpleEventAggregator>();
        services.AddSingleton<IDependencyResolver>(c =>
            new FuncDependencyResolver(type => c.GetRequiredService(type))); services.AddGraphQLHttp();
        services.AddGraphQLWebSocket<OrdersSchema>();
        services.AddMvc();
    }

So then I can write it like this

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IOrderService, OrderService>();
        services.BatchSingleton(new[] {
            "I*Service",
            "Order*",
            "Customer*"
        });

        services.AddSingleton<IEventAggregator, SimpleEventAggregator>();
        services.AddSingleton<IDependencyResolver>(c =>
            new FuncDependencyResolver(type => c.GetRequiredService(type))); services.AddGraphQLHttp();
        services.AddGraphQLWebSocket<OrdersSchema>();
        services.AddMvc();
    }

Installation

  • .NET CLI
dotnet add package BatchDI
# Just only install this if using ASP.NET Core
dotnet add package BatchDI.AspNetCore
  • Package Manager
PM> Install-Package BatchDI
PM> Install-Package BatchDI.AspNetCore
for nightly build (if really needed)

In nuget.config before installing

<configuration>
  <packageSources>
    <add key="BatchDI Package" value="https://ci.appveyor.com/nuget/batch-di" />
  </packageSources>
</configuration>

Usage

See Example folder for more complete example usage.

In *.csproj

  <ItemGroup>
    <PackageReference Include="BatchDI" Version="1.1.0" />
    <!-- Just only add this if using ASP.NET Core -->
    <PackageReference Include="BatchDI.AspNetCore" Version="1.1.0" />
  </ItemGroup>

Then to import

using BatchDI;
using BatchDI.AspNetCore;

In general, this library has 2 way of usage:

Base Usage

Use this method if you want to do custom Dependency Injection.
using BatchDI;
.
.
BatchDI.BatchInject(
    filter: "*Service",
    injector: _implementation =>
    {
        if (_implementation.Name.Contains("My"))
        {
            service.AddSingleton(_class, new MyBaseService(Configuration["MyConfig"])));
        }
    }
);

// or

BatchDI.BatchInject(
    filter: "I*Service",
    injector: (_interface, _class) => service.AddSingleton(_interface, _class),
);

Using Helper Method

ASP․NET Core

This method have same functionality as ASP.NET Dependency Injection but without doing repetitive typing.

  • In Startup.cs
using Microsoft.Extensions.DependencyInjection;
using BatchDI.AspNetCore;
.
.
public void ConfigureServices(IServiceCollection services)
{
    service.BatchSingleton("*Service", new[] {"BlacklistOneService", "BlacklistTwoService"})
           .BatchTransient("*Type", "BlacklistOneType");

    service.BatchScoped("*Query");

    // For custom dependency injection
    service.BatchInject(lambdaFunction, "*Service", new[] {"BlacklistOneService", "BlacklistTwoService"});
}
Workaround for fix error in Integration Test.

Use SetBatchDIEntryPoint to set the EntryAssembly

_server = new TestServer(new WebHostBuilder().SetBatchDIEntryPoint<Startup>().UseStartup<Startup>());

API Reference

Arguments/Parameters
Parameter Description Type Default value
injector (lambda) implement callback for custom DI Action<Type>,
Action<Type, Type>
filter list or glob pattern for specify which class name to inject string,
string[]
blacklist (optional) list or glob pattern for specify which class name not to be injected string,
string[]
parallel (optional) if the startup time become slower, try to set this true bool false
nested (optional) choose if also to inject nested class bool true

BatchDI

Method Description Return
BatchInject(injector =>{}, filter, blacklist?, parallel?, nested?) implement custom dependency injection based on filter pattern and blacklist
SetEntryAssembly(Assembly assembly) Try to set this this in case there is an error

BatchDI.AspNetCore

This library extend IServiceCollection usage by adding additional method for batch/multiple Dependency Injection in one method call.

Method Description Return
BatchSingleton(filter, blacklist?, parallel?, nested?) Batch/MultipleAdd version of AddSingleton IServiceCollection
BatchTransient(filter, blacklist?, parallel?, nested?) Batch/MultipleAdd version of AddTransient IServiceCollection
BatchScoped(filter, blacklist?, parallel?, nested?) Batch/MultipleAdd version of AddScoped IServiceCollection

Support

See CONTRIBUTING.md for contributing directly via:

License

MIT License

About

⚡Dependency Injection without type⌨️ fatigue✍️

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages