:
. Ninject 4.0.0, - (). Ninject 3.3.x .
:
@Steven
ASP.NET Core 2.0 Ninject ( 3.3.x, 4.0). Missing-Core-DI-Extensions Git repo, dotnetjunkie.
Ninject:
1) AspNetCoreExtensions.cs AspNetCoreMvcExtensions.cs .
2) , DI: TestService
, ITestService
:
public class TestService : ITestService
{
public int Data { get; private set; }
public TestService()
{
Data = 42;
}
}
public interface ITestService
{
int Data { get; }
}
Startup.cs
, :
1)
private readonly AsyncLocal<Scope> scopeProvider = new AsyncLocal<Scope>();
private IKernel Kernel { get; set; }
private object Resolve(Type type) => Kernel.Get(type);
private object RequestScope(IContext context) => scopeProvider.Value;
2) ConfigureServices(IServiceCollection services)
( )
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddRequestScopingMiddleware(() => scopeProvider.Value = new Scope());
services.AddCustomControllerActivation(Resolve);
services.AddCustomViewComponentActivation(Resolve);
3) Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
( )
Kernel = RegisterApplicationComponents(app, loggerFactory);
4) :
private IKernel RegisterApplicationComponents(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
Kernel = new StandardKernel();
foreach (var ctrlType in app.GetControllerTypes())
{
Kernel.Bind(ctrlType).ToSelf().InScope(RequestScope);
}
Kernel.Bind<ITestService>().To<TestService>().InScope(RequestScope);
Kernel.BindToMethod(app.GetRequestService<IViewBufferScope>);
Kernel.Bind<ILoggerFactory>().ToConstant(loggerFactory);
return Kernel;
}
private sealed class Scope : DisposableObject { }
5) BindToMethod
public static class BindingHelpers
{
public static void BindToMethod<T>(this IKernel config, Func<T> method) => config.Bind<T>().ToMethod(c => method());
}
6) DI, , . Ninject (, ConfigureRequestScoping
)
IKernel
4, IReadOnlyKernel IKernelConfiguration ( ).
1) (IReadOnlyKernel
)
private readonly AsyncLocal<Scope> scopeProvider = new AsyncLocal<Scope>();
private IReadOnlyKernel Kernel { get; set; }
private object Resolve(Type type) => Kernel.Get(type);
private object RequestScope(IContext context) => scopeProvider.Value;
2) 3)
4) :
private IReadOnlyKernel RegisterApplicationComponents(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
IKernelConfiguration config = new KernelConfiguration();
foreach (var ctrlType in app.GetControllerTypes())
{
config.Bind(ctrlType).ToSelf().InScope(RequestScope);
}
config.Bind<ITestService>().To<TestService>().InScope(RequestScope);
config.BindToMethod(app.GetRequestService<IViewBufferScope>);
config.Bind<ILoggerFactory>().ToConstant(loggerFactory);
return config.BuildReadonlyKernel();
}
5) IKernelConfiguration
public static class BindingHelpers
{
public static void BindToMethod<T>(this IKernelConfiguration config, Func<T> method) => config.Bind<T>().ToMethod(c => method());
}