Spring.NET 1.3.1 新特性探索系列1——ASP.NET MVC的依赖注入

本文内容纲要:Spring.NET 1.3.1 新特性探索系列1——ASP.NET MVC的依赖注入

  Spring.NET 1.3.1的程序集Spring.Web.Mvc提供对ASP.NET MVC程序的整合。其中SpringControllerFactory类继承自DefaultControllerFactory,以便于实现Spring.NET对Controller的管理

  

SpringControllerFactory

publicclass SpringControllerFactory : DefaultControllerFactory

{

privatestatic IApplicationContext _context;

///


/// Gets the application context.

///


///The application context.

publicstatic IApplicationContext ApplicationContext

{

get

{

if (_context ==null|| _context.Name != ApplicationContextName)

{

if (string.IsNullOrEmpty(ApplicationContextName))

{

_context = ContextRegistry.GetContext();

}

else

{

_context = ContextRegistry.GetContext(ApplicationContextName);

}

}

return _context;

}

}

///


/// Gets or sets the name of the application context.

///


///

/// Defaults to using the root (default) Application Context.

///

///The name of the application context.

publicstaticstring ApplicationContextName { get; set; }

///


/// Creates the specified controller by using the specified request context.

///


///The context of the HTTP request, which includes the HTTP context and route data.

///The name of the controller.

///A reference to the controller.

///The parameter is null.

///The parameter is null or empty.

publicoverride IController CreateController(RequestContext requestContext, string controllerName)

{

IController controller;

if (ApplicationContext.ContainsObjectDefinition(controllerName))

{

controller = ApplicationContext.GetObject(controllerName) as IController;

}

else

{

controller =base.CreateController(requestContext, controllerName);

}

AddActionInvokerTo(controller);

return controller;

}

///


/// Retrieves the controller instance for the specified request context and controller type.

///


///The context of the HTTP request, which includes the HTTP context and route data.

///The type of the controller.

///The controller instance.

///

/// is null.

///

/// cannot be assigned.

///An instance of cannot be created.

protectedoverride IController GetControllerInstance(RequestContext requestContext, Type controllerType)

{

IController controller =null;

if (controllerType !=null)

{

var controllers = ApplicationContext.GetObjectsOfType(controllerType);

if (controllers.Count >0)

{

controller = (IController)controllers.Cast().First().Value;

}

}

else

{

//pass to base class for remainder of handling if can't find it in the context

controller =base.GetControllerInstance(requestContext, controllerType);

}

AddActionInvokerTo(controller);

return controller;

}

///


/// Adds the action invoker to the controller instance.

///


///The controller.

protectedvirtualvoid AddActionInvokerTo(IController controller)

{

if (controller ==null)

return;

if (typeof(Controller).IsAssignableFrom(controller.GetType()))

{

((Controller)controller).ActionInvoker =new SpringActionInvoker(ApplicationContext);

}

}

}

  让我们开始实现对ASP.NET依赖注入的实现。

  一、首先引用程序集Spring.Web.Mvc.dll,此程序可以脱离Spring.NET独立使用。

  二、修改MvcApplication类,继承SpringMvcApplication。

  让我们看下SpringMvcApplication类的代码

SpringMvcApplication

publicabstractclass SpringMvcApplication : HttpApplication

{

///


/// Handles the Start event of the Application control.

///


///The source of the event.

///The instance containing the event data.

protectedvirtualvoid Application_Start(object sender, EventArgs e)

{

RegisterAreas();

RegisterRoutes(RouteTable.Routes);

}

///


/// Configures the instance.

///


///

/// You must override this method in a derived class to control the manner in which the

/// is configured.

///

protectedvirtualvoid ConfigureApplicationContext()

{

}

///


/// Executes custom initialization code after all event handler modules have been added.

///


publicoverridevoid Init()

{

base.Init();

//the Spring HTTP Module won't have built the context for us until now so we have to delay until the init

ConfigureApplicationContext();

RegisterSpringControllerFactory();

}

///


/// Registers the areas.

///


///

/// Override this method in a derived class to modify the registered areas as neeeded.

///

protectedvirtualvoid RegisterAreas()

{

AreaRegistration.RegisterAllAreas();

}

///


/// Registers the routes.

///


///

/// Override this method in a derived class to modify the registered routes as neeeded.

///

protectedvirtualvoid RegisterRoutes(RouteCollection routes)

{

// This IgnoreRoute call is provided to avoid the trouble of CASSINI passing all req's thru

// ASP.NET (and thus the controller pipeline) during debugging

// see http://stackoverflow.com/questions/487230/serving-favicon-ico-in-asp-net-mvc and elsewhere for more info

routes.IgnoreRoute("{*favicon}", new { favicon =@"(.*/)?favicon.ico(/.*)?" });

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

);

}

///


/// Registers the controller factory with the Mvc Framework.

///


protectedvirtualvoid RegisterSpringControllerFactory()

{

ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));

}

}

  这样,我们在增加Route规则的时候,可以重写RegisterRoutes方法。

MvcApplication

publicclass MvcApplication : SpringMvcApplication

{

protectedoverridevoid RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

"Default", // 路由名称

"{controller}/{action}/{id}", // 带有参数的 URL

new { controller ="Home", action ="Index", id = UrlParameter.Optional } // 参数默认值

);

}

}

  三、给HomeController增加一个属性。

HomeController

publicclass HomeController : Controller

{

publicstring Message { get; set; }

public ActionResult Index()

{

ViewData["Message"] =this.Message;

return View();

}

public ActionResult About()

{

return View();

}

}

  四、增加Controller配置Controllers.xml。

Controllers.xml

  五、配置Web.config

Web.config

       

  运行效果

  博库出处:http://www.cnblogs.com/GoodHelper/archive/2010/12/22/SpringNet131Mcv.html

  欢迎转载,但需保留版权。

  代码下载

本文内容总结:Spring.NET 1.3.1 新特性探索系列1——ASP.NET MVC的依赖注入

原文链接:https://www.cnblogs.com/GoodHelper/archive/2010/12/22/SpringNet131Mcv.html

以上是 Spring.NET 1.3.1 新特性探索系列1——ASP.NET MVC的依赖注入 的全部内容, 来源链接: utcz.com/z/362600.html

回到顶部