所以,我一直在關注史蒂芬·桑德森的書叫臨ASP.NET MVC框架,和我運行到一個例外:SportsStore:MVC編程問題[城堡WindsorControllerFactory]
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
Line 16: HttpContext.Current.RewritePath(Request.ApplicationPath, false);
Line 17: IHttpHandler httpHandler = new MvcHttpHandler();
Line 18: httpHandler.ProcessRequest(HttpContext.Current);
Line 19: HttpContext.Current.RewritePath(originalPath, false);
Line 20: }
Source File: C:\Users\Stephen\Documents\Visual Studio 2008\Projects\SportsStore\WebUI\Default.aspx.cs Line: 18
這裏是我的WindsorControllerFactory代碼:
public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;
// The constructor
// 1. Sets up a new IoC container
// 2. Registers all components specified in web.config
// 3. Registers all controller types as components
public WindsorControllerFactory()
{
// Instantiate a container, taking configuration from web.config
container = new WindsorContainer(
new XmlInterpreter(new ConfigResource("castle"))
);
// Also register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
container.AddComponentWithLifestyle(t.FullName, t, Castle.Core.LifestyleType.Transient);
}
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
我的Global.asax.cs代碼:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());
}
而且在web.config值:
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,
Castle.Windsor"/>
</configSections>
<castle>
<properties>
<myConnStr>Server=.\SQLEXPRESS;Database=SportsStore;Trusted_Connection=yes;</myConnStr>
</properties>
<components>
<component id="ProdsRepository"
service="DomainModel.Abstract.IProductsRepository, DomainModel"
type="DomainModel.Concrete.SqlProductsRepository, DomainModel">
<parameters>
<connectionString>#{myConnStr}</connectionString>
</parameters>
</component>
</components>
</castle>
謝謝大家! -Steve
您知道Windsor具有流暢的專用註冊API,對嗎?您不必使用自定義反射。 – 2010-06-30 21:35:11