This post might be useful if you perform auto-registration of your components through an interface. Like this:
AllTypes.Of<IController>().FromAssembly(typeof(Application).Assembly).Configure(reg =>reg.Named(reg.Implementation.Namespace.Split('.').Last().ToLowerInvariant() + "." +reg.Implementation.Name.ToLowerInvariant()).LifeStyle.Transient),
This snippet of code finds all types that implement the IController interface. This would be any controller in your MVC App that implements the Controller base class (Controller implements IController). In this instance the namespace could be something like:
namespace DonnFelker.Example{public class HomeController : Controller{// Actions here}}
Therefore the auto-registration will give this controller a named instance of “example.homecontroller” in the container. This allows me to access it via named instance in the controller. The other thing it does is allow me to access it via the config file.
Why Do That?
I would want to do this because lets assume my application has 30 controllers. I want them all registered in my container, yet I need Example.HomeController to have a setting injected into it. Maybe this is a location of a test server that I use for some ajax communication and I do not want to put this into the appSettings of the config file. I want to put it directly into the object that needs it. An example of this class would look like this:
namespace DonnFelker.Example{public string PreviewUrlFormat { get; set; } public class HomeController : Controller{// Actions here}}
In this case I want to set “PreviewUrlFormat” through my config. I do not want the rest of my controllers to have this property injected. I would use this property as part of view data for some action (perhaps to do some JQuery action in the background against that url). Perhaps I’m doing some rendering at the time the user is looking at an admin page.
Since I’m auto-registring this component I cannot inject anything into it in the config unless I make an entry. Here’s the entry I provided to have PreviewUrlFormat injected:
<componentid="example.homecontroller"service="DonnFelker.Example.HomeController, DonnFelker.Example" ><parameters><PreviewUrlFormat>http://www.example.com/previewfile?fileid={0}</PreviewUrlFormat></parameters></component>
This snippet of configuration will look for the example.homecontroller named instance and then inject the PreviewUrlFormat into the class.
I have omitted the “type” from this component injection because I’m finding the instance via its id.
I hope this helps someone out there.
Leave a Reply
You must be logged in to post a comment.