সোমবার, ১৮ নভেম্বর, ২০১৩

Implementing Repository, Unit of Work and Ioc in CRUD Application



ü  Repository I Unit of Work Gi example Gi cy‡iv As‡ki cieZ©x Ask-
ü  GLb Avgiv Service Layer define Ki‡ev|
ü  Service Layer UI perspective G application's scope I available operation set define K‡i|
ü  Bnv application Gi business logic controlling transaction mg~n encapsulate K‡i Ges operation mg~‡ni implementation coordinate K‡i|
ü  d‡j Controller classes mg~n light nq Ges Dnv‡Z (Controller classes mg~‡n) †Zgb business logic ivLv nq bv|
ü  Service layer ‡K Avgiv business logic layer wnmv‡e e¨envi Ki‡Z cvwi Ges application rule mg~n‡K encapsulate Ki‡Z cvwi|
ü  GLb Avgiv application business logic Gi Rb¨ student service interface Ges Dnvi corresponding student service class define Ki‡ev
ü  cÖ_‡g Avgiv student service interface define Kwi-

using System;

using System.Collections.Generic;

using System.Linq;  

using System.Text;

using CodeFirstEntities;

 

namespace CodeFirstServices.Interfaces

{

    public interface IStudentService

    {

        IEnumerable<Student> GetStudents();

        Student GetStudentById(int id);

        void CreateStudent(Student student);

        void UpdateStudent(Student student);

        void DeleteStudent(int id);

        void SaveStudent();

    }

}

ü  GB interface G Avgiv Get Student Details, List, Update and Delete Student etc. method signature mg~n define K‡iwQ|
ü  GLb D³ interface A_©vr IStudentService ‡K inherit K‡i StudentService class create Kwi hvi definition wb¤œiƒc-
using System.Collections.Generic;
using CodeFirstData.DBInteractions;
using CodeFirstData.EntityRepositories;
using CodeFirstEntities;
using CodeFirstServices.Interfaces;

namespace CodeFirstServices.Services
{
    public class StudentService : IStudentService
    {
         private readonly IStudentRepository _studentRepository;
        private readonly IUnitOfWork _unitOfWork;
        public StudentService(IStudentRepository studentRepository, IUnitOfWork unitOfWork)
        {
            this._studentRepository = studentRepository;
            this._unitOfWork = unitOfWork;
        } 
        #region IStudentService Members

        public IEnumerable<Student> GetStudents()
        {
            var students = _studentRepository.GetAll();
            return students;
        }

        public Student GetStudentById(int id)
        {
            var student = _studentRepository.GetById(id);
            return student;
        }

        public void CreateStudent(Student student)
        {
            _studentRepository.Add(student);
            _unitOfWork.Commit();
        }

        public void DeleteStudent(int id)
        {
            var student = _studentRepository.GetById(id);
            _studentRepository.Delete(student);
            _unitOfWork.Commit();
        }

        public void UpdateStudent(Student student)
        {
            _studentRepository.Update(student);
            _unitOfWork.Commit();
        }

        public void SaveStudent()
        {
            _unitOfWork.Commit();
        }

        #endregion
    }
}
ü  StudentService class constructor Gi ga¨ w`‡q Repository I Unit of Work Gi dependency inject Kiv n‡q‡Q| Bnv Constructor Dependency Injection.
Resolve Dependencies
o   cÖ_‡g Avgiv current HttpContext G container store Ki‡Z Unity Gi Rb¨ GKwU custom lifetime manager create Ki‡ev hvi definition wb¤œiƒc-
namespace CodeFirstPortal.IoC
{
public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
    {
        public override object GetValue()
        {
            var assemblyQualifiedName = typeof (T).AssemblyQualifiedName;
            if (assemblyQualifiedName != null)
                return HttpContext.Current.Items[assemblyQualifiedName];
            return null;
        }
 
        public override void RemoveValue()
        {
            var assemblyQualifiedName = typeof (T).AssemblyQualifiedName;
            if (assemblyQualifiedName != null)
                HttpContext.Current.Items.Remove(assemblyQualifiedName);
        }
 
        public override void SetValue(object newValue)
        {
            var assemblyQualifiedName = typeof (T).AssemblyQualifiedName;
            if (assemblyQualifiedName != null)
                HttpContext.Current.Items[assemblyQualifiedName] = newValue;
        }
 
        public void Dispose()
        {
            RemoveValue();
        }
    }
}
}

o   Then Dependency mg~n resolve Kivi Rb¨ Avgiv KwZcq class create Ki‡ev
o   CustomControllerActivator
§  ASP.NET MVC 3 ‡Z byZb GKwU  new interface introduce Kiv n‡q‡Q hvi bvg IControllerActivator.
§   GB interface custom behavior mn controller mg~n activate allow K‡i|
§  Bnv‡K dependency injection purpose G I use Kiv hvq|
§  Dependency resolver use K‡i IControllerActivator interface discover Kiv hvq|
§  GLb Avgiv IControllerActivator interface inherit K‡i custom controller activator class create Ki‡ev hvi definition wb¤œiƒc n‡e-

using System;
using System.Web.Mvc;
namespace CodeFirstPortal.IoC
{
    public class CustomControllerActivator : IControllerActivator
    {       
        IController IControllerActivator.Create(
            System.Web.Routing.RequestContext requestContext,
            Type controllerType)
        {
            return DependencyResolver.Current
                .GetService(controllerType) as IController;
        }     
    }
}


o   UnityControllerFactory
ü  We also create a UnityController Factory and Configure contract and concrete types of unity in global.asax file.
ü  Avgiv UnityController Factory define Kwi hvi definition wb¤œiƒc-
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace CodeFirstPortal.IoC
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
        IUnityContainer container;
        public UnityControllerFactory(IUnityContainer container)
        {
            this.container = container;
        }
        protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
        {
            IController controller;
            if (controllerType == null)
                throw new HttpException(
                        404, String.Format(
                            "The controller for '{0}' could not be found" + "or it does not implement IController.",
                        reqContext.HttpContext.Request.Path));

            if (!typeof(IController).IsAssignableFrom(controllerType))
                throw new ArgumentException(
                        string.Format(
                            "Requested type is not a controller: {0}",
                            controllerType.Name),
                            "controllerType");
            try
            {
                controller= container.Resolve(controllerType) as IController;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(String.Format(
                                        "Error resolving the controller {0}",
                                        controllerType.Name), ex);
            }
            return controller;
        }

    }
o   UnityDependencyResolver
§  ASP.NET MVC 3 IDependencyResolver bv‡g GKwU new interface introduce K‡i‡Q hvnv‡Z GetService Ges GetServices bv‡gi `yBwU method signature define Kiv n‡q‡Q |
§  GetService method use K‡i singly registered service resolve K‡i Ges GetServices method use K‡i multiply registered service resolve K‡i|
§  Implementations of the IDependencyResolver interface should delegate to the underlying dependency injection container to provide the registered service for the requested type.
§  IDependencyResolver interface ‡K Implement K‡i requested type Gi Rb¨ registered service provide Ki‡Z underlying dependency injection container G interface delegate n‡e|
§   hLb requested type Gi †Kvb registered service bv _v‡K ZLb GetServices method empty collection return Ki‡e|
§   Let’s create a custom dependency resolver class by deriving from IDependencyResolver intreface in order to working with Unity to providing dependency injection.
§  GLb Avgiv IDependencyResolver interface ‡K implement K‡i GKwU custom dependency resolver class Ki‡ev hvnv‡Z Unity dependency injection provide Ki‡Z cv‡i| D³ class definition wb¤œiƒc-
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace CodeFirstPortal.IoC
{
public class UnityDependencyResolver : IDependencyResolver
{       
    IUnityContainer container;      
    public UnityDependencyResolver(IUnityContainer container)
    {
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch
        {              
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch
        {               
            return new List<object>();
        }
    }
}
}


Global.asax
·         DependencyResolver class Gi SetResolver method Gi Øviv dependency injection container Gi registration point provide Kiv nq|
·         GB method G Avgiv Unity 2.0 Gi mv‡_ dependency injection provide Kivi Rb¨ UnityDependencyResolver class ‡K configure Ki‡ev|
·          SetResolver method ‡h‡Kvb dependency injection container Gi mv‡_ KvR Ki‡e|
using System.Web.Mvc;
using System.Web.Routing;
using CodeFirstData.DBInteractions;
using CodeFirstData.EntityRepositories;
using CodeFirstPortal.IoC;
using CodeFirstServices.Interfaces;
using CodeFirstServices.Services;
using Microsoft.Practices.Unity;
 
namespace MvcPortal
{
   
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
 
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
 
        }
 
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
 
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            IUnityContainer container = GetUnityContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
 
        private IUnityContainer GetUnityContainer()
        {
            //Create UnityContainer         
            IUnityContainer container = new UnityContainer()
            .RegisterType<IDBFactory, DBFactory>(new HttpContextLifetimeManager<IDBFactory>())
            .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())
            .RegisterType<IStudentService, StudentService>(new HttpContextLifetimeManager<IStudentService>())
            .RegisterType<IStudentRepository, StudentRepository>(new HttpContextLifetimeManager<IStudentRepository>());
            return container;
        }
    }
}

·         GLb Avgiv web.config file G connection string define Ki‡ev hvnv wb¤œiƒc-
<connectionStrings>
    <add name="CodeFirstContext"
    connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=CodeFirstApp;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=true"
    providerName="System.Data.SqlClient"/>
  </connectionStrings>
·         GLb Avgiv Controller wb‡q KvR Ki‡ev-
·         Application First time hLb run Ki‡e ZLb home Controller ‡K default controller wnmv‡e call KviY global.asax G default controller wnmv‡e home Controller ‡K define Kiv n‡q‡Q|
·         When the Index action of the controller is called we redirect it to our Student Controller, which straight away returns view to show lists of students if they exist, since it is the first time we are creating the controller, it shows an empty list, the controller method of Student fetches the student list from the database, but first it creates the database, thus acheiving our objective.
·         hLb home controller Gi Index action call Kiv n‡e ZLb Student Controller G redirect n‡e Ges students  lists  display Ki‡e| GRb¨ Avgiv home Controller Gi index  method wb¤œiƒ‡c define Ki‡ev-
public ActionResult Index()
 {
   return RedirectToAction("List", "Student");
 }

Note : Student Controller ‡K hw` First time create K‡i call Kiv nq Z‡e cÖ_gevi students  list empty _vK‡e KviY Student Controller Gi method database ‡_‡K student list fetch Ki‡e| †h‡nZz cÖ_gevi Project run Kiv‡j DbSet Database create Ki‡e ZvB Controller method empty list return Ki‡e|
  • GLb Avgiv Student Controller define Ki‡ev hvnvi operation action mg~n wb¤œiƒc-
using System;
using System.Linq;
using System.Web.Mvc;
using CodeFirstEntities;
using CodeFirstServices.Interfaces;
 
namespace CodeFirstPortal.Controllers
{
    public class StudentController : Controller
    {
        private readonly IStudentService _studentService;
 
        public StudentController(IStudentService studentService)
        {
            this._studentService = studentService;
        }
 
        [HttpGet]
        public ActionResult Details(int? id)
        {
            var studentDetails = _studentService.GetStudentById((int) id);
            if (studentDetails == null) throw new ArgumentNullException("Not Found");
            return View(studentDetails);
        }
 
        [HttpGet]
        public ActionResult Delete(int? id)
        {
            var studentDetails = _studentService.GetStudentById((int) id);
            if (studentDetails == null) throw new ArgumentNullException("Not Found");
            return View(studentDetails);
        }
 
        [HttpPost]
        public ActionResult Delete(Student student)
        {
            _studentService.DeleteStudent(student.StudentId);
            return RedirectToAction("List", "Student");
        }
 
 
        [HttpGet]
        public ActionResult Edit(int? id)
        {
            var studentDetails = _studentService.GetStudentById((int) id);
            if (studentDetails == null) throw new ArgumentNullException("Not Found");
            return View(studentDetails);
        }
 
        [HttpPost]
        public ActionResult Edit(Student student)
        {
            _studentService.UpdateStudent(student);
            return RedirectToAction("List", "Student");
        }
 
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult Create(Student student)
        {
            var studentModel = new Student()
                                   {
                                       Address = student.Address,
                                       Country = student.Country,
                                       Name = student.Name,
                                       Age = student.Age,
                                       Email = student.Email
                                   };
            _studentService.CreateStudent(studentModel);
            return RedirectToAction("List", "Student");
        }
 
        [HttpGet]
        public ActionResult List()
        {
            var students = _studentService.GetStudents();
            if (students.Any())
            {
                return View("List", students);
            }
 
            return View("List");
        }
    }
}
·         [HttpGet] Gi action mg~n database ‡_‡K data Get Ki‡e Avi [HttpPost] Gi action mg~n database G data Post Ki‡e|
·         Controller Gi Constructor G dependency inject K‡i Student Service ‡K initialize Kiv n‡q‡Q| Direct ‡Kvb instance create Kiv nq bvB|
  • GLb Avgiv Controller Gi cÖwZwU action Gi Rb¨ view create Ki‡ev|
  • GRb¨ cÖwZwU controller action Gi Dci right click -> create view.
  • d‡j automatically view create n‡q hv‡e  (Constructor name Gi same name Gi folder G GB view create n‡e|)
  •  GLb Avgiv Project run KivB|

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন