Thursday, 9 July 2015

Changes required to be done for implementing Dependency injection in WebAPI or MVC project

Below are the changes required to be done for implementing Dependency injection in WebAPI or MVC project.

References required:

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Mvc;
using IOCLibrary;



global.asax changes:
This change is required only for Web project.

public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            #region "General settings"
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }


WebApiConfig.cs changes:

In below example, we are implementing Dependency injection on classes which are used for handling requests
(For e.g. Inspector.cs , HttpsRquestValidator.cs).
If there are no such classes in your project then these change is not required.
This change is required only for WebAPI or MVC project.


namespace WebAPITest
{

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var container = UnityConfig.GetConfiguredContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

//To validate request data
            var Inspector = container.Resolve<Inspector>();
            Inspector.InnerHandler = new HttpControllerDispatcher(config);
           
//Global request handler -applicable to all the requests
            var validator = container.Resolve<HttpsRquestValidator>();

            config.DependencyResolver = new IocContainer(container);

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }, null, Inspector);

            config.MessageHandlers.Add(validator);
        }
    }
}


//App_Start/UnityWebActivator.cs changes
This change is required only for WebAPI or MVC project.

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnityWebActivator), "Shutdown")]

namespace WebAPITest
{
    /// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
    public static class UnityWebActivator
    {
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start()
        {
            var container = UnityConfig.GetConfiguredContainer();

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
           
        }

        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
    }
}


// UnityConfig.cs changes
This file is used for maintaining list of all classes used in project with their mapped interface.


public class UnityConfig
    {
        #region Unity Container
        private static readonly Lazy<IUnityContainer> Container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });
        public static IUnityContainer GetConfiguredContainer()
        {
            return Container.Value;
        }
        #endregion
       
        public static void RegisterTypes(IUnityContainer container)
        {
            //load classess
            container.RegisterType<HomeController>();
            container.RegisterType<IFileSystem, FileSystem>();
        }
    }


Create IOCLibrary using below classes:
If there are more than project then this library will be useful or you could use below classes in project itself.

public class ScopeContainer : IDependencyScope
    {
        protected IUnityContainer Container;

        public ScopeContainer(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            Container = container;
        }

        public object GetService(Type serviceType)
        {
            if (Container.IsRegistered(serviceType))
            {
                return Container.Resolve(serviceType);
            }
            return null;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (Container.IsRegistered(serviceType))
            {
                return Container.ResolveAll(serviceType);
            }
            return new List<object>();
        }

        public void Dispose()
        {
            Container.Dispose();
        }
    }

    public class IocContainer : ScopeContainer, IDependencyResolver
    {
        public IocContainer(IUnityContainer container)
            : base(container)
        {
        }

        public IDependencyScope BeginScope()
        {
            var child = Container.CreateChildContainer();
            return new ScopeContainer(child);
        }

    }

Wednesday, 8 July 2015

How to abstract dependency in OOPS


Below rules should be followed in OOPS to implement Dependency Inversion Principle.

·         All member variables in a class must be interfaces or abstracts.
·         All concrete class packages must connect only through interface/abstract class’s packages.
·         No class should derive from a concrete class.
·         No method should override an implemented method.
·         All variable instantiation requires the implementation of a Creational pattern as the Factory Method or the Factory pattern, or the more complex use of an Injection framework.




What is dependency inversion principle?

In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling software modules.
This principle helps to create loosely coupled application.
 The principle states:
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend on details. Details should depend on abstractions.

How to register ASP.Net with IIS

Installing and registering ASP.Net with IIS and add ASP.Net 4.0 Application Pool in IIS


Why do we need to install and register ASP.Net in IIS?
To allow IIS server to serve ASP.Net pages.


What will happen if ASP.Net is not registered with IIS?
If Asp.Net is not registered with IIS then below error will occur while accessing ASP.net website
Error Description:
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.


How to verify if ASP.Net is registered with IIS?
Once the ASP.Net is registered the IIS will show ASP.Net 4.0 Application pools.


How to install .Net framework (For installing ASP.NET)?
You will need to download and install the necessary .Net Framework on your system using below link Download .Net Frameworks.


What is “aspnet_regiis.exe”?
aspnet_regiis.exe” is used to register ASP.Net in IIS server which is available after successful installation of .Net Framework.


Where to find “aspnet_regiis.exe”?
aspnet_regiis.exeis available at below location after successful installation of .Net Framework.
If your window is installed in C drive you could find the aspnet_regiiis.exe at the following locations.
32 BIT
C:\Windows\Microsoft.NET
64 BIT
C:\Windows\Microsoft.NET\Framework64
Now based on whether your System is 32 BIT or 64 BIT and the .Net Framework version you want to register, you need to get into the .Net Framework Folder.
Assume if your Windows is 64 BIT and you need to register .Net Framework 4 then path for aspnet_regiis.exe will be
“C:\Windows\Microsoft.NET\Framework64\v4.0.30319\”



How to register ASP.Net with IIS server using “aspnet_regiis.exe”?
Follow below steps:
<1> Open windows menu options by clicking on bottom left “Start” button (Or Press windows key).
<2>  Type “CMD” in search box at bottom in menu, It will show cmd.exe in context menu.
<3> Right click on “cmd.exe” and choose Run as administrator from the context menu.
<4> On the command prompt, navigate to the Directory that has the “aspnet_regiis.exe” file for that you need to type.
       CD < aspnet_regiis.exe  file path>
For eg.
              CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319\

<5> Type the following command and hit enter to register ASP.Net with IIS.
aspnet_regiis –i


Once the ASP.Net is installed in IIS, you will see ASP.Net 4.0 Application pools in the IIS server



How to register ASP.Net of different versions with IIS server using “aspnet_regiis.exe”?

Follow same steps mentioned above to register other .Net Framework versions.