Showing posts with label Ninject. Show all posts
Showing posts with label Ninject. Show all posts

Thursday, August 25, 2016

Using Unity IoC with constructor parameters

I recently decided to switch my IoC container from Ninject to Unity for my ASP.NET Web API Web Application because the Ninject IoC container has poor support for Web API and has not been updated/refreshed in several years.

So, naturally, when I began switching my code over from Ninject over to Unity, one of the questions that immediately came up was how to use constructor parameters for my types in Unity?

Well, after doing some quick searching and experimentation, I came up with this solution:


It is as simple as that!

Monday, August 1, 2016

Using Ninject Extensions Conventions

If you are using Ninject, you may find yourself duplicating a lot of code for binding interfaces to their respective classes.

Fortunately, Ninject has a NuGet package which can take a lot of that tedious work away and bind interfaces to classes automatically!

The name of the Ninject package is called Ninject.Extensions.Conventions:



Once you have installed the NuGet package, you can add the following code to the RegisterServices method of your NinjectWebCommon.cs file:


That is all that is needed to get your Ninject project up and running!

Using Ninject with Generic Types

I have been using Ninject for years to bind Interfaces to Classes, or even Classes to instances of Classes, but I had never earlier bound a generic Interface to a generic Class!  In my case, I was creating a Generic Repository class and needed to bind it using Ninject.

After doing some searching through StackOverflow discussions, I came across this solution which worked well:



As you can tell from the above code sample, the only main difference in the code base is to use the typeof casting operator to get the generic type to resolve correctly!

Friday, July 29, 2016

Sequence contains no elements while using Ninject

I was recently working on an ASP.NET Web API project that used Ninject as its IoC container when I was suddenly faced with this error message:


As you can see from above, the error message provided no real insight as to what might be the root cause of the problem!

Therefore, I decided to do some further digging into the documentation for Ninject and came across this article: https://github.com/ninject/Ninject.Web.Common/wiki/Setting-up-an-IIS-hosted-web-application

Based on this documentation, I needed to make sure that my NuGet package reference to Ninject.Web.Common.WebHost was correct.

Of course, when I went into my packages.config file, the NuGet package reference was listed and it was also listed as installed in NuGet Package Manager.

However, based on the error message, I figured there was some problem with this installation and its corresponding references so I removed the line from packages.config in my Web API project and re-installed the Ninject.Web.Common.WebHost NuGet package reference.

As you can already probably guess, this did the trick for me and resolved this very elusive Ninject problem!!

NOTE:  Another time I have encountered this problem has been due to invalid assemblies in the bin folder of my ASP.NET Web API project.  Simple deleting the bin folder of my ASP.NET Web API project and rebuilding my solution also resolved the problem!

Thursday, July 28, 2016

Implementing the Repository Pattern in C# with Entity Framework

If you are looking to implement the Repository Pattern in C#, you may find lots and lots and LOTS of conflicting solutions about how to implement the Repository Pattern in your own application.

If you just do a quick search just on MSDN, you will find articles such as the following:

https://blogs.msdn.microsoft.com/wriju/2013/08/23/using-repository-pattern-in-entity-framework/

http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

If you look through the examples above, you will see that they offer different solutions to the same Repository Pattern problem.  However, the second example provides the ability to create a Generic Repository which is much more appealing than creating a different repository for each class in your entire data model!

Unfortunately, the MSDN example lacks a definition of a generic interface which GenericRepository implements.  Looking at the code, you can derive your own IRepository interface, but the example still lacks support for a Dependency Injection or IoC container.  As you will readily notice, the example directly requires an implementation of SchoolContext to be created.  The way in which the example gets around direct creation of the SchoolContext is by using a Unit of Work class which handles the creation of this instance.  While the Unit of Work class can be useful in aggregating multiple repositories, it may not make much sense for instances when you simply need a single repository, which is why an IoC container is very useful!

So how exactly do you get Ninject to work in this scenario?

For Ninject, you simply use the following code to inject your SchoolContext instance:


You can simply add the following code to your RegisterServices method inside of your NinjectWebCommon.cs file and this should do the trick for you!

Monday, July 25, 2016

Ensure that you have defined a binding for HttpConfiguration only once

I was recently working on adding Ninject to an ASP.NET Web API web application, when I suddenly encountered the following error message:



Well, as it turns out, after adding the Ninject.Web.WebApi.WebHost NuGet package reference, I also had a reference to Ninject.Web.WebApi which was causing the HttpConfiguration to be injected twice!

I had originally added the Ninject.Web.WebApi.WebHost NuGet package reference so that the NinjectWebCommon.cs file would be added automatically to my App_Start directory for injecting my dependencies.

Once that file was added, I no longer needed this NuGet package reference, so I went ahead and removed it and I could successfully browse my ASP.NET Web API Web Application once again!

Thursday, April 21, 2016

Injecting string arguments using Ninject

I recently had a requirement to inject strings into a constructor argument using an IoC container such as Ninject.

Unfortunately, I had always used Ninject in the past to inject dependencies that were based on interfaces, so how was I supposed to inject primitive types such as strings?

Well, fortunately, using Ninject, it is surprisingly simple!!

I just used the following code:


kernel.Bind<IHttpClientWrapper>().To<HttpClientWrapper>().WithConstructorArgument("userName", "johndoe"); 

That was all that was needed!!

Monday, April 11, 2016

Injecting HttpContext into an ASP.NET MVC Web Application using Ninject

If you have ever struggled with using HttpContext in your ASP.NET MVC Web Applications in regards to developing applications that can be easily tested, then you will be happy to know that this problem can be readily solved using HttpContextBase and an IoC container such as Ninject!

In my particular situation, I needed to use Cookies in my application therefore I created a class similar to the following:


public class CookieManager : ICookieManager
    {
        private HttpContextBase _context;

        public CookieManager(HttpContextBase context)
        {
            _context = context;
        }

        public HttpCookie GetCookie(string cookieName)
        {
            HttpCookie cookie = null;

            if (_context != null)
            {
                cookie = _context.Request.Cookies[cookieName];
            }


            return cookie;
        }//method: GetCookie()
}
        

Now the problem arose as to how to use an IoC container such as Ninject to handle injecting the proper HttpContext?

First of all, if you do not inject your HttpContext, you will receive an error something like shown below:





Well, there are 2 possible ways of accomplishing this:


kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current));

The above method will inject HttpContext into any class that is dependent on HttpContextBase, therefore, making your development relatively easy to maintain going forward.

If you want to be more explicit about your HttpContextBase dependencies, you can instead do something like the following:


kernel.Bind<ICookieManager>().To<CookieManager>().WithConstructorArgument("context", ctx => new HttpContextWrapper(HttpContext.Current));

Therefore, as you can see, now you can easily inject an instance of HttpContext using HttpContextBase as well as easily Unit Test your applications using a Mocking Framework such as Moq by leveraging an interface such as the ICookieManager interface I have used in my above code samples.

That is all there is to it!!

Tuesday, September 22, 2015

Using Ninject Dependency Injection in an ASP.NET Web API Web Application

I have been using Ninject Dependency Injection in my ASP.NET Web API Projects by simply doing the following things in the past:

  1. Install the Ninject Web Host for WebApi 2 NuGet package: https://www.nuget.org/packages/Ninject.Web.WebApi.WebHost/
  2. Add the necessary DI mappings in the RegisterServices method of the NinjectWebCommon.cs file found in the App_Start folder

However, even after doing all of this, I experienced the following error message:

An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.

I had earlier been using an older release of Ninject and did not experience this problem, so I decided to check what version I was using and I was using v. 3.2.4.

As a test to see if a new problem was introduced, I decided to use the older version of Ninject from NuGet (https://www.nuget.org/packages/Ninject.Web.WebApi/3.2.3) by running the following command in the Package Manager Console:

Install-Package Ninject.Web.WebApi -Version 3.2.3

Sure enough, my Web API Controller resolved correctly once I reverted to the older version of Ninject Web API!!

<ArrayOfstring><string>value1</string><string>value2</string></ArrayOfstring>

Therefore, there were some problems in an earlier release of Ninject.Web.Common (v. 3.2.0) that caused the use of the NinjectWebCommon.cs file by itself to no longer be sufficient.

You can use a NinjectDependencyResolver class to workaround this problem as described in this article (http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api), but if you are having the same problem, it is best to make sure you are using at least v. 3.2.3 of Ninject.Web.Common or a later release.

 

Monday, April 13, 2015

Using Ninject to inject HttpContext into an ASP.NET MVC Web Application

Injecting HttpContext into an ASP.NET MVC Web Application is a common requirement even with the latest version of ASP.NET MVC 5 since ASP.NET MVC still has underlying pinnings directly dependent on HttpContext.

If you search across the web, this is a somewhat difficult issue to tackle when dealing with Dependency Injection.

Though the solutions are pretty difficult to find on the Internet, fortunately, the actual implementations are relatively easy.

For example, to inject HttpContext into an ASP.NET MVC Web Application, you can use one of the following lines in your NinjectWebCommon.cs file:
kernel.Bind<HttpContext>().ToMethod(ctx => HttpContext.Current).InRequestScope();
kernel.Bind<HttpContextBase>().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InRequestScope();

If you are interested in injecting something like the current User into your MVC Web Application, you can use something like this:

 


kernel.Bind<IIdentity>().ToMethod(ctx => HttpContext.Current.User.Identity);

If you need a class that is dependent on HttpContext (such as the creation and management of Cookies), you can use something like this:



kernel.Bind<ICookieManager>().To<CookieManager>().WithConstructorArgument("context", ctx => HttpContext.Current);

That is all there is to injecting HttpContext using Ninject in your ASP.NET MVC Web Applications! 



Thursday, January 29, 2015

Getting started with Ninject for ASP.NET MVC and ASP.NET Web API

If you are using ASP.NET MVC or ASP.NET Web API, you are probably interested in using a Dependency Injection Framework such as Ninject to help you with Unit Testing your Controllers.

Well, fortunately, getting started with Ninject in your ASP.NET MVC or ASP.NET Web API projects is relatively easy!

First, either create an ASP.NET MVC or ASP.NET Web API project.

Once you have done that, you will need to add NuGet packages to your project to add the Ninject reference assemblies.

For an ASP.NET MVC web application, you will want to add Ninject.MVC5 and ninject.extensions.conventions:







For an ASP.NET Web API project, you will want to add Ninject integration for WebApi 2 and ninject.extensions.conventions:


You will also have to add a NuGet package reference for WebActivator:



For your Web API project, the NinjectWebCommon.cs file will not automatically be added to your project, so you may have to copy and paste it from a sample ASP.NET MVC project.  The NinjectWebCommon.cs file should be placed in the App_Start folder of your ASP.NET MVC web application.

In the NinjectWebCommon.cs file in your project, you can then add your kernel.Bind code to inject all of the appropriate dependencies in the RegisterServices method.

That is all there is to it!!