As I was preparing a POC for my new project, I stumble upon an idea of using dependency injection / IOC. This is to facilitate the property injection to my Repository or Service classes. Here is the snapshot of the code
Global.asax
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; using Monday.Data; using Monday.Data.Repositories; using WebFormsMvp.Binder; using WebFormsMvp.Unity; namespace Monday { public class Global : System.Web.HttpApplication { private readonly IUnityContainer _container; public Global() : base() { _container = new UnityContainer(); } void Application_Start(object sender, EventArgs e) { _container.RegisterInstance<MondayEntities>( new MondayEntities(), new ContainerControlledLifetimeManager()); _container.RegisterType<ICountryRepository, CountryRepository>( new ContainerControlledLifetimeManager()); UnityServiceLocator locator = new UnityServiceLocator(_container); ServiceLocator.SetLocatorProvider(() => locator); PresenterBinder.Factory = new UnityPresenterFactory(_container); }
The implementation of the Unity is pretty normal except that I use the ServiceLocator to encapsulate calls to the UnityContainer. Developers may get instance using the following code.
ICountryRepository repo =
ServiceLocator.Current.GetInstance<ICountryRepository>();
As for codes that want to utilize Property Injection they can implement it in the following way
public class CountryScriptPresenter : Presenter<ICountryScriptView> { private ICountryScriptView _view; public CountryScriptPresenter(ICountryScriptView view) : base(view) { _view = view; _view.Load += new EventHandler(OnLoad); } [Dependency] public ICountryRepository CountrySource { get; set; } private void OnLoad(object sender, EventArgs e) { if (CountrySource == null) throw new ApplicationException("CountryRepository is null or not defined."); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(sw, CountrySource.GetList()); _view.Model.List = sb.ToString(); ; } }
The Dependency attribute will handle the injection of the object
Advertisement