public interface IWatch { { DateTime GetTime(); } }
以下Watch类实现了IWatch接口 –
public class Watch:IWatch { public DateTime GetTime() { return DateTime.Now; } }
WebApi控制器 – WatchController如下 –
public class WatchController : ApiController { private readonly IWatch _watch; public WatchController() { _watch = new Watch(); } //http://localhost:48036/api/Watch public string Get() { var message = string.Format("The current time on the server is: {0}", _watch.GetTime()); return message; } }
public class Watch:IWatch { public DateTime GetTime() { return DateTime.Now; } }
ApiController WatchController.cs的定义如下: –
public class WatchController : ApiController { private readonly IWatch _watch; public WatchController(IWatch watch) { _watch = watch; } public string Get() { var message = string.Format("The current time on the server is: {0}", _watch.GetTime()); return message; } }
public class WatchInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { //Need to Register controllers explicitly in your container //Failing to do so Will receive Exception: //> An error occurred when trying to create //a controller of type //> 'xxxxController'. Make sure that the controller has a parameterless //> public constructor. //Reason::Basically, what happened is that you didn't register your controllers explicitly in your container. //Windsor tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null. //It is forced to return null, because Web API forces it to do so due to the IDependencyResolver contract. //Since Windsor returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception. //This exception message is misleading and doesn't explain the real cause. container.Register(Classes.FromThisAssembly() .BasedOn() .LifestylePerWebRequest());*** container.Register( Component.For().ImplementedBy() ); } }
static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); // This will run in design mode, so all your VS design data will come from here if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register(); } // This will run REAL stuff, in runtime else { SimpleIoc.Default.Register(); } // You register your classes, so the framework can do the injection for you SimpleIoc.Default.Register(); ... }