Kasutades VS2010RC versiooni näeb asi välja järgmine.

Keskkond:

Visual studio 2010 RC .NET 4.0 RC projekt
Castle Windsor 2.1.1
Asp.Net MVC2 RC
Klasside teek DataModels, mis sisaldab kaustas Abstract liidest ITestRepository ja kaustas Concrete klassi TestRepository, mis selle liidese omadusi kasutab.

Sammud:

1. Loo WindsorControllerFactory klass

public class WindsorControllerFactory:DefaultControllerFactory
{
    private WindsorContainer container;

    public WindsorControllerFactory()
    {
        container=new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));

        var controllerTypes = from types in Assembly.GetExecutingAssembly().GetTypes()
                              where typeof (IController).IsAssignableFrom(types)
                              select types;

        foreach (var c in controllerTypes)
        {
             container.AddComponentLifeStyle(c.FullName,c, LifestyleType.Transient);
        }
    }

    protected override IController GetControllerInstance(
        System.Web.Routing.RequestContext requestContext,
        System.Type controllerType)
    {
        return (IController)container.Resolve(controllerType);
    }
}

2. Muuda web.config faili.
Lisa configuration tagi alla configSections tag ja castle tag. Ning system.web tagi alla httpModules

<configuration>
  <configSections>
    <section name="castle"
             type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
  </configSections>
  <castle>
    <components>
      <component id="ProdsRepository"
                 <!--Registreerib liidese-->
                 service ="DataModels.Abstract.ITestRepository,DataModels"
                 <!--Annab vaste-->
                 type="DataModels.Concrete.TestRepository,DataModels"
                 lifestyle="PerWebRequest">
      </component>
    </components>
  </castle>
  ...
    <httpModules>
      <add name="PerRequestLifestyle"
           type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />
    </httpModules>
  </system.web>
  ...

3. Sea WindsorControllerFactory põhi Controller’ite loojaks.

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());

Tulemus:

Tulemuseks on see, et kui me kusagil loome MVC2 Controlleri näiteks:

public class TestController : Controller
{
    private ITestRepository tests;

    public TestController(ITestRepository tests)
    {
        this.tests= tests;
    }
    //TODO: write methods
}

Ei pea me enam kusagile sisse kirjutama new TestController(new TestRepository()) vaid Castle Windsor teeb seda meie eest. Nüüd saame etteantavat repository muuta, web.config faili kaudu ja mitte kogu rakendust uuesti kompileerides.

Advertisements