Windsor Configuration Standard Practices - configuration

The app I inherited uses the fluent interface for configuring our Windsor container, and it's this big glob o' configuration that's pretty disgusting.
In the past I created an extension method container.AddModule and then created modules that were passed in the container and registered services a la StructureMap for the different "modules" of my system that need configuration.
container.AddModule(new FooModule());
...
public class FooModule : IWindsorModule
{
public Register(IWindsorContainer container)
{
container.Register(/*Windsor's Ridiculous Fluent Syntax*/);
}
}
Is that what facilities are in Windsor? Are the analogous to StructureMap modules or are they extension points for adding super-magic to Windsor?
What is the best-practice for making your container config more modular and less insane?

Check out IWindsorInstaller:
http://stw.castleproject.org/Windsor.Installers.ashx
http://www.castlecasts.com/Episodes/9/Show/using-windsor
Also if you're coming from StructureMap this article might be useful.
There's a thin line with Facilities but in general, facilities are intended to be used for more complex stuff that requires custom configuration / several internal components, etc.

Related

How to pass configuration parameters to SimpleInjector packaging?

So SimpleInjector now has a packaging nuget that you can use to isolate different aspects of root composition.
Say I have a configurable composition root in a library that is reused by multiple projects in an application. For example, in an Azure solution I might have a Web role and a Worker role which share a large set of the same dependencies for the most part, but with slightly different configuration options depending on the consumer. When I compose the root, I can pass in a plain old RootCompositionSettings object with properties that tell SimpleInjector how to register dependencies.
However, I am not sure how (or if) I can pass these settings to an IPackage instance. Is it possible to pass custom settings to a SimpleInjector package, and if so, how?
I see that the standard practices for registering packages is to invoke either
container.RegisterPackages(); // scans all loaded assemblies for IPackage
// or
container.RegisterPackages(IEnumerable<Assembly>) // specific assemblies only
...so how can we pass parameters into the packaging instance(s)? Is there some way to do it via the container?
The trick here is to pass the information on with the container to the package. You can do this by using the container's Items dictionary, that is much like ASP.NET's HttpContext.Items collection. This can be done as follows:
using SimpleInjector.Advanced;
container.SetItem(typeof(RootCompositionSettings), settings);
container.RegisterPackages();
Now inside your packages, you can do the following:
var settings =
(RootCompositionSettings)container.GetItem(typeof(RootCompositionSettings));
Please note that:
SetItem and GetItem are extension methods that are located in the SimpleInjector.Advanced namespace. Those methods allow you to access the (internal) Items dictionary.
You can pass in any key you like. Passing in typeof(RootCompositionSettings) is just convenient in this case, but not required.
If you need to call the settings in more places, it might be useful to create a more specific extension method that allows you to access the setting instance, but that's up to you.
Another option is to not use the IPackage interface and the SimpleInjector.Packaging library at all. In most cases it doesn't really add anything and you could simply define a public static method in the assembly that does the same as a package does. For instance:
public static class BusinessLayerBootstrapper
{
public static void Bootstrap(Container container, ScopedLifestyle scopedLifestyle,
RootCompositionSettings settings)
{
// Here the same logic as what you would write in your package.
}
}
Most applications are not that dynamic that you need to load assemblies dynamically and the startup project usually has a hard reference to all the other assemblies. In that case it is perfectly sane to simply call a static method.
And even if you have the requirement of dynamically loading assemblies and allowing them to register their stuff in the container, it's quite trivial to build your own IPackage abstraction instead:\
// Your own IPackage interface
public interface IPackage
{
void RegisterServices(Container container, RootCompositionSettings settings);
}
// Your own extension method
public static void RegisterPackages(this Container container,
RootCompositionSettings settings)
{
var packages =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetExportedTypes()
where typeof(IPackage).IsAssignableFrom(type)
where !type.IsAbstract
select (IPackage)Activator.CreateInstance(type);
packages.ToList().ForEach(p => p.RegisterServices(container, settings));
}
In fact, except for some extra validations and filtering out dynamic assemblies, the SimpleInjector.Packaging project is not much more than this.

Resolving a dependency while supplying values for downstream dependencies

I've been running into endless problems attempting to use Windsor with Web API and injecting HttpRequestMessage into downstream dependencies of a controller. Since I've tried all the matching answers on Stackoverflow, I'd like to ask the question in a different way:
In Castle Windsor, how can I resolve a component instance while supplying a value for a downstream dependency? That is, the supplied value is required by a component that is required by the component being resolved.
For context, I'm trying to inject HttpRequestMessage so that I can use it to resolve the request context (primarily to resolve an absolute URL).
Edit I'd also like to point out that I don't currently have a dependency on Web Host / System.Web and I'd rather not change that.
A proper approach is to
Create IMyDesiredRouteParameterProvider
Implement it. Get the current request inside it and get the url
Register it and inject it in the desired dependent class via constructor.
I made myself such an implementation and I can say that this way it works fine. You can make Web.Infrastructure assembly and put the implementation there. Or put both the interface and the implementation there if you are going to reference it from another web module.
using System;
using System.Web;
namespace RouteParameterProvider
{
interface IMyRouteParameterProvider
{
string GetRouteParameter();
}
public class ControllerActionMethodRouteParameterProvider : IMyRouteParameterProvider
{
public string GetRouteParameter()
{
string Parameter = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"] as string;
if (string.IsNullOrEmpty(Parameter))
{
throw new InvalidOperationException();
}
return Parameter;
}
}
}
You can get every possible thing that the Request Context contains from :
HttpContext.Current.Request.RequestContext
And it will be better if you rethink your design decision :
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
Containers are to be initialized at runtime and then used to resolve.
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
It sounds like you want to register an item with the container at runtime, post-startup. In general, this is not a good practice--registration should be a discrete event that happens when the app is fired up, and the container's state should not be changed during runtime.
Dependency Injection is about resolving service components, not runtime state--state is generally passed via methods (method injection). In this case it sounds like your LinkGenerator component needs access to the ambient state of the request.
I'm not that familiar with HttpRequestMessage, but this answer seems to show that it is possible to retreive it from HttpContext.Current. You could make this a method on your LinkGenerator class, or wrap this call in a separate component that gets injected into LinkGenerator (HttpRequestMessageProvider?). The latter would be my preferred method, as it allows LinkGenerator to be more testable.
Given the lack of a clean way of doing this and Web API not providing information as to the hosted endpoint beyond per-request context objects, I ended up injecting the base url from configuration.
Is this library by Mark Seemann the answer? In the description he writes explicitly :
This approach enables the use of Dependency Injection (DI) because the
request can be injected into the services which require it.
Then gives an example :
// Inside an ApiController
var uri = this.Url.GetLink(a=> a.GetById(1337));
By which you can then pass the URL down the road in the service that you have injected in the controller.
UPDATE :
Mark Seemann wrote about the same exact problem here:
"Because HttpRequestMessage provides the context you may need to
compose dependency graphs, the best extensibility point is the
extensibility point which provides an HttpRequestMessage every time a
graph should be composed. This extensibility point is the
IHttpControllerActivator interface:..."
This way you can pass request context information to a component deep in the object graph by getting from the HttpRequestMessage and passing it to the DI container.
Just take a look at the interface of IHttpControllerActivator.
The WEB API framework gets the IHttpControllerActivator through DependencyResolver. You probably already replaced it by your CastleWindsorDependencyResolver. Now you have to implement and register your HttpControllerActivator and register it.
When the WEB API framework gets IHttpControllerActivator from DependencyResolver (your Castle Windsor DR) and calls IHttpControllerActivator.Create() it will pass you the HttpRequestMessage. You can get your info from there and pass it to the your CastleDR before you call Resolve(typeof(MyController)) which will resolve the whole object graph - that means you will have MyHttpContextInfo to inject in your XYZComponent deep in the resolution stack.
This way tou are passing the arguments in the last possible moment but it is still possible. In Castle Windsor I make such passing of arguments though CreationContext.AdditionalArguments["myArgument"];.

Managing connections with Generic Repository pattern

I am building a site using entity framework 4.1 and mvc3. I am using the Generic Repository pattern:
http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle. I use ninject to inject my concretes repositories to the controllers.
My problem is that each of my dbcontext different and I cannot run complex queries without the code shouting something like "different contexts cannot be used in the same query". I tried using the "singleton" approach but then code shouted something like "tried to enter a disposed object (null reference exception)".
Does anyone have an idea of what I'm doing wrong?
The Singleton pattern is an anti-pattern that should be avoided. It leads to hard to test code with all kinds of side effects (for example, a disposed DbContext).
The UnitOfWork manages operations on different repositories. It will keep track of all the changes that are made and then it will write those changes in the right order to your database. The DbContext already implements the UnitOfWork pattern (Altough it's nicer to hide the DbContext behind a custom UnitOfWork interface).
If you are already using dependency injection trough NInject you are almost their! You should change the constructors of your Repository to take a DbContext:
public class MyRepository
{
private _unitOfWork;
public MyRepository(DbContext unitOfWork)
{
_unitOfWork = unitOfWork;
}
....
}
If you then wire the DbContext to NInject with a InRequestScope mode everything should work. Your DbContext will then be shared by all Repositories and Ninject will dispose of it at the end of your request.
Not sure if I'm getting your question or not, but your repositories should be able to work within a "Unit of Work" which would have a single dbcontext.
I find the best place to start this unit of work is on the begin request, which you can setup in your global.asax ( and the end request for tear down )

Castle Windsor Typed Factory Facility equivalents

do any other .NET IoC containers provide equivalent functionality to the typed factory facility in Castle Windsor?
e.g. if I am using an abstract factory pattern in a WPF application:
public class MyViewModel
{
private IAnotherViewModelFactory factory;
public void ShowAnotherViewModel()
{
viewController.ShowView(factory.GetAnotherViewModel());
}
}
I don't want to have to create a manual implementation of IAnotherViewModelFactory for every type of ViewModel I wish to show, I want the container to take care of this for me.
AutoFac has a feature called Delegate Factories, but as far as I can tell, it works only with delegates, and not interfaces.
I haven't encountered anything similar to Castle's Typed Factory Facility in neither StructureMap nor Unity, but that doesn't necessarily mean that they're not there...
The only way I can imagine that something like this could be implemented for interfaces is via a dynamic proxy. Since Castle Windsor has a Dynamic Proxy, but few other containers have anything similar, this might go a long way to explain why this feature isn't ubiquitous.
Unity also offers interception capabilities, so it must have some sort of dynamic proxy implementation, but I'm pretty sure it doesn't have anything equivalent to Typed Factories. Compared to other containers, Unity is rather basic.
In Autofac you can implement typed factories on top of the delegate approach Mark mentions. E.g.
class AnotherViewModelFactory : IAnotherViewModelFactory {
Func<AnotherViewModel> _factory;
public AnotherViewModelFactory(Func<AnotherViewModel> factory) {
_factory = factory;
}
public AnotherViewModel GetAnotherViewModel() {
return _factory();
}
}
If this class is registered with the container, along with AnotherViewModel Autofac will provide the Func<AnotherViewModel> implementation implicitly:
builder.RegisterType<AnotherViewModel>();
builder.RegisterType<AnotherViewModelFactory>()
.As<IAnotherViewModelFactory>();
Practically any interface you can implement using Typed Factory Facility can be implemented in Autofac using this kind of approach. The primary difference is that the Windsor implementation configures the factory through the component registration API, while in Autofac the factory is a component in its own right.
For more sophisticated examples you might like to look at: http://code.google.com/p/autofac/wiki/RelationshipTypes and http://nblumhardt.com/2010/01/the-relationship-zoo/.
I have recently implemented an equivalent of Castle Windsor Typed Factories for Unity. You can find the project at https://github.com/PombeirP/Unity.TypedFactories, and the NuGet package at http://nuget.org/packages/Unity.TypedFactories.
The usage is the following:
unityContainer
.RegisterTypedFactory<IFooFactory>()
.ForConcreteType<Foo>();
The parameter matching is done by name, which is fine for my needs, although the library could easily be extended to support other needs.

How to get instance of service in Windsor Castle

In a multilayer application (ASP MVC: UI project, DAL project) i registered in web.config the components.
Now i have this problem: Unit of Work pattern has do be implemented and i need to get the current instance of a particular service. The registration of the services happened in the UI project, but i need to get the current instance of this service in the DAL project. How do i get this reference?
In the UI project i already needed a way to get something resolved:
container = new WindsorContainer(
new XmlInterpreter(new ConfigResource("castle"))
);
personRepository= container.Resolve<IPersonRepository>();
Would it be OK to use the same technique in the DAL project? If yes, should i write the configuration in a separate file, so that it can be accessed by all the layers(projects)?
Sorry for this (i think) naive question but it's my first project using Castle and i think i don't understand the big picture of it!
Code snippet would help a lot.
Thanks in advance!
In a nutshell: one container instance per application, one container configuration that has all the components you need for the application. If you need a service in your DAL, inject the appropriate service interface in your DAL class via constructor (if the dependency is required) or setter (if the dependency is optional).
Try really hard to avoid using a static IoC gateway, it hides the true dependencies of a component and it hampers testability.
See these related questions:
Usage of IoC Containers; specifically Windsor
Is it correct to have many Castle Windsor containers per application if those containers belong to different tiers?
Have a look at this article. It shows you how to write a static class that performs dependency resolution using Castle Windsor. You should consider putting this class in a separate project that can be referenced from both your UI and DAL projects to allow code reuse. As the article explains, your class should provide a bootstrapper facility that initializes your IoC container. In your case, this would look like:
public static class IoC
{
private WindsorContainer _container;
public static void Initialize()
{
_container = new WindsorContainer(
new XmlInterpreter(new ConfigResource("castle"))
);
}
}
The bootstrapper would be invoked from the application startup event in your UI projects Global.asax file.
The other methods for obtaining instances of objects from the container would be as per the article.