<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ninject asp.net &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/ninject-asp-net/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Tue, 08 May 2018 07:25:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>ninject asp.net &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Wiring up Ninject with ASP.NET Core 2.0</title>
		<link>https://topreviewhostingasp.net/how-to-wiring-up-ninject-with-asp-net-core-2-0/</link>
					<comments>https://topreviewhostingasp.net/how-to-wiring-up-ninject-with-asp-net-core-2-0/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Tue, 08 May 2018 07:25:35 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[ASP.NET Hosting]]></category>
		<category><![CDATA[asp.net tips]]></category>
		<category><![CDATA[asp.net tutorial]]></category>
		<category><![CDATA[ninject asp.net]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=1541</guid>

					<description><![CDATA[Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software&#8217;s architecture, your code will become easier to write, reuse, test, and modify. To test if the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="http://www.ninject.org/">Ninject</a> is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software&#8217;s architecture, your code will become easier to write, reuse, test, and modify.</p>
<p>To test if the injector is working correctly, create a service that implements an interface</p>
<pre class="lang:default decode:true ">    public interface ITestService
    {
        string GetData();
    }

    public class TestService : ITestService
    {
        public string GetData()
        {
            return "some magic string";
        }
    }</pre>
<h4>Download the package from Nuget</h4>
<p>Using the package manager console <code>Install-Package Ninject -Version 3.3.4</code></p>
<p>Using dotnet cli <code>dotnet add package Ninject --version 3.3.4</code></p>
<h4>Add these members to <code>Startup.cs</code> class as shown below</h4>
<pre class="lang:default decode:true ">    private readonly AsyncLocal&lt;Scope&gt; scopeProvider = new AsyncLocal&lt;Scope&gt;();
    private IKernel Kernel { get; set; }

    private object Resolve(Type type) =&gt; Kernel.Get(type);
    private object RequestScope(IContext context) =&gt; scopeProvider.Value;  

    private sealed class Scope : DisposableObject { }</pre>
<h4>Add the following binding in the end of <code>ConfigureServices</code> (<code>Startup.cs</code>)</h4>
<p><code>services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();</code></p>
<h4>Create class <code>RequestScopingStartupFilter</code> implementing the <code>IStartupFilter</code> interface</h4>
<pre class="lang:default decode:true ">    public sealed class RequestScopingStartupFilter : IStartupFilter
    {
        private readonly Func&lt;IDisposable&gt; requestScopeProvider;

        public RequestScopingStartupFilter(Func&lt;IDisposable&gt; requestScopeProvider)
        {
            if (requestScopeProvider == null)
            {
                throw new ArgumentNullException(nameof(requestScopeProvider));
            }

            this.requestScopeProvider = requestScopeProvider;
        }

        public Action&lt;IApplicationBuilder&gt; Configure(Action&lt;IApplicationBuilder&gt; nextFilter)
        {
            return builder =&gt;
            {
                ConfigureRequestScoping(builder);

                nextFilter(builder);
            };
        }

        private void ConfigureRequestScoping(IApplicationBuilder builder)
        {
            builder.Use(async (context, next) =&gt;
            {
                using (var scope = this.requestScopeProvider())
                {
                    await next();
                }
            });
        }
    }</pre>
<h4>Create a static class <code>AspNetCoreExtensions</code> with the following extension method</h4>
<pre class="lang:default decode:true ">    using System;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.DependencyInjection;

    public static class AspNetCoreExtensions
    {
        public static void AddRequestScopingMiddleware(this IServiceCollection services, 
            Func&lt;IDisposable&gt; requestScopeProvider)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (requestScopeProvider == null)
            {
                throw new ArgumentNullException(nameof(requestScopeProvider));
            }

            services
                .AddSingleton&lt;IStartupFilter&gt;(new
                    RequestScopingStartupFilter(requestScopeProvider));
        }
    }</pre>
<h4>Configure to use the middleware in <code>ConfigureServices</code>(in the end of the method)</h4>
<p><code>services.AddRequestScopingMiddleware(() =&gt; scopeProvider.Value = new Scope());</code></p>
<h4>Create a file <code>Activators.cs</code> with the following</h4>
<pre class="lang:default decode:true ">   public sealed class DelegatingControllerActivator : IControllerActivator
        {
            private readonly Func&lt;ControllerContext, object&gt; controllerCreator;
            private readonly Action&lt;ControllerContext, object&gt; controllerReleaser;

            public DelegatingControllerActivator(Func&lt;ControllerContext, object&gt; controllerCreator,
                Action&lt;ControllerContext, object&gt; controllerReleaser = null)
            {
                this.controllerCreator = controllerCreator ?? 
                    throw new ArgumentNullException(nameof(controllerCreator));
                this.controllerReleaser = controllerReleaser ?? ((_, __) =&gt; { });
            }

            public object Create(ControllerContext context) =&gt; this.controllerCreator(context);
            public void Release(ControllerContext context, object controller) =&gt;             
                this.controllerReleaser(context, controller);
        }</pre>
<h4>Add the following extension method to <code>AspNetCoreExtensions.cs</code></h4>
<pre class="lang:default decode:true ">        public static void AddCustomControllerActivation(this IServiceCollection services,
            Func&lt;Type, object&gt; activator)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            if (activator == null) throw new ArgumentNullException(nameof(activator));

            services.AddSingleton&lt;IControllerActivator&gt;(new DelegatingControllerActivator(
                context =&gt; activator(context.ActionDescriptor.ControllerTypeInfo.AsType())));
        }</pre>
<h4>Append the following to the end of <code>ConfigureServices</code></h4>
<p><code>services.AddCustomControllerActivation(Resolve);</code></p>
<h4>Add another class to <code>Activators.cs</code></h4>
<pre class="lang:default decode:true ">        public sealed class DelegatingViewComponentActivator : IViewComponentActivator
        {
            private readonly Func&lt;Type, object&gt; viewComponentCreator;
            private readonly Action&lt;object&gt; viewComponentReleaser;

            public DelegatingViewComponentActivator(Func&lt;Type, object&gt; viewComponentCreator,
                Action&lt;object&gt; viewComponentReleaser = null)
            {
                this.viewComponentCreator = viewComponentCreator ?? 
                    throw new ArgumentNullException(nameof(viewComponentCreator));
                this.viewComponentReleaser = viewComponentReleaser ?? (_ =&gt; { });
            }

            public object Create(ViewComponentContext context) =&gt;
                this.viewComponentCreator(context.ViewComponentDescriptor.TypeInfo.AsType());

            public void Release(ViewComponentContext context, object viewComponent) =&gt;
                this.viewComponentReleaser(viewComponent);
        }</pre>
<h4>And another extension method in <code>AspNetCoreExtensions.cs</code></h4>
<pre class="lang:default decode:true ">       public static void AddCustomViewComponentActivation(this IServiceCollection services, 
            Func&lt;Type, object&gt; activator)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            if (activator == null) throw new ArgumentNullException(nameof(activator));

            services.AddSingleton&lt;IViewComponentActivator&gt;(
new DelegatingViewComponentActivator(activator));
        }</pre>
<p>then call it form <code>ConfigureServices</code> (should be the last invoked)</p>
<p>This is what <code>ConfigureServices</code> should look like now</p>
<pre class="lang:default decode:true ">        public void ConfigureServices(IServiceCollection services)
        {
            // Other configurations

            services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();

            services.AddRequestScopingMiddleware(() =&gt; scopeProvider.Value = new Scope());
            services.AddCustomControllerActivation(Resolve);
            services.AddCustomViewComponentActivation(Resolve);

        }</pre>
<h4>Create an <code>ApplicationBuilderExtensions.cs</code> with a static class in it</h4>
<pre class="lang:default decode:true ">    using System;
    using System.Globalization;
    using System.Linq;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc.ApplicationParts;
    using Microsoft.AspNetCore.Mvc.Controllers;
    using Microsoft.Extensions.DependencyInjection;
    using Ninject;

    public static class ApplicationBuilderExtensions
    {
        public static void BindToMethod&lt;T&gt;(this IKernel config, Func&lt;T&gt; method)
 =&gt; config.Bind&lt;T&gt;().ToMethod(c =&gt; method());

        public static Type[] GetControllerTypes(this IApplicationBuilder builder)
        {
            var manager = builder.ApplicationServices.GetRequiredService&lt;ApplicationPartManager&gt;();

            var feature = new ControllerFeature();
            manager.PopulateFeature(feature);

            return feature.Controllers.Select(t =&gt; t.AsType()).ToArray();
        }

        public static T GetRequestService&lt;T&gt;(this IApplicationBuilder builder) where T : class
        {
            if (builder == null) throw new ArgumentNullException(nameof(builder));

            return GetRequestServiceProvider(builder).GetService&lt;T&gt;();
        }

        private static IServiceProvider GetRequestServiceProvider(IApplicationBuilder builder)
        {
            var accessor = builder.ApplicationServices.GetService&lt;IHttpContextAccessor&gt;();

            if (accessor == null)
            {
                throw new InvalidOperationException(      
          typeof(IHttpContextAccessor).FullName);
            }

            var context = accessor.HttpContext;

            if (context == null)
            {
                throw new InvalidOperationException("No HttpContext.");
            }

            return context.RequestServices;
        }
    }</pre>
<p>Add the following method in <code>Startup</code> class</p>
<pre class="lang:default decode:true ">        private IKernel RegisterApplicationComponents(IApplicationBuilder app)
        {
            // IKernelConfiguration config = new KernelConfiguration();
            var kernel = new StandardKernel();

            // Register application services
            foreach (var ctrlType in app.GetControllerTypes())
            {
                kernel.Bind(ctrlType).ToSelf().InScope(RequestScope);
            }

            // This is where our bindings are configurated
             kernel.Bind&lt;ITestService&gt;().To&lt;TestService&gt;().InScope(RequestScope);            

            // Cross-wire required framework services
            kernel.BindToMethod(app.GetRequestService&lt;IViewBufferScope&gt;);

            return kernel;
        }</pre>
<p>and call it from <code>Configure</code> (in the beginning)</p>
<p><code>this.Kernel = this.RegisterApplicationComponents(app);</code></p>
<h4>Create a <code>TestController</code> to see if our DI works</h4>
<pre class="lang:default decode:true ">    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly ITestService testService;

        public ValuesController(ITestService testService)
        {
            this.testService = testService;
            this.factory = factory;
        }

        [HttpGet]
        public IActionResult Get()
        {
            var result = this.testService.GetData();

            return this.Ok(result);
        }
    }</pre>
<p>Place a breakpoint in the constructor of our <code>TestService</code> and in the <code>Get</code>action to see the magic.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-wiring-up-ninject-with-asp-net-core-2-0/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
