How do i pass a dynamic dependency to a typedfactory instance at the bottom of the decorator chain? - castle-windsor

I am fond of using decorator chains instead of inheritance, and as long as my services have Singleton or Transient lifestyles (and their dependencies are scoped in the same manner) this works perfectly. I've started to use the TypedFactoryFacility to generate factories for services which require some sort of input which can not be resolved through the ioc container. My headache starts when something deep in the decorator chain requires a factory and Windsor refuses to pass inline dependencies down the inheritance chain. As I understand this is by design, but I don't agree that this breaks encapsulation when you are using a factory which explicitly states what you need to produce the output (I think Windsor should pass inline dependencies to components which are factory resolvable, but I'm guessing its not that straight forward. Anyway, at the end of the day I end up exposing my decorator chain like this:
public ISessionInputOutput Create(Session session)
{
IServerInput baseInput = _inputFactory.GetBaseInput(session.CommunicationSocketStream);
IServerInput threadSafeInput = _inputFactory.GetThreadSafeInput(baseInput);
IServerOutput output = _outputFactory.Create(session.CommunicationSocketStream);
ISessionInputOutput baseIO = _sessionIOFactory.GetBaseIO(baseInput, output);
ISessionInputOutput commandHandlerIO = _sessionIOFactory.GetCommandHandlerIO(baseIO, session);
ISessionInputOutput errorHandlingIO = _sessionIOFactory.GetErrorHandlingIO(commandHandlerIO, session);
_releaseInfo.Add(errorHandlingIO, new CreatedIOInformation(baseInput, threadSafeInput, output, baseIO, commandHandlerIO));
return errorHandlingIO;
}
In the example I am using 3 factory proxies, and manually combine the output to produce the decorator chain.
I can't simply use ServiceOverrides as I usually do to introduce new services. This doesn't feel right and I am hoping that someone can suggest a better solution what I've used above.
I've also tried to solve this by using child containers, but this introduces a bit more ioc details into the stack than I like.

If you really feel you need to enable passing down the dependencies you can enable that by overriding RebuildContextForParameter method in DefaultDependencyResolver and passing true for propagateInlineDependencies.
Be aware that this is a double-edged sword. You can also filter this out and enable this behavior only when you're resolving one of the few services for which you need this, and stick to the default behavior for all other.

Related

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"];.

Fluently choosing which component to inject

I have some components implementing the same interface and I would like to chose which one gets injected to my Repository.
Component.For<IRepository>().ImplementedBy<Repository>().<whatShouldGoHere>()
I thought I had this working with DependsOn but now I saw that DependsOn are for static dependecies such as strings. Is the IHandlerSelector the only way forward? I would rather have the declaration inline with the component registration. Maybe a factory method? Are there any recommendations?
Edit
Example Constructor
public PersitentRepository(Func<ISession,string> sessionFactory)
Digging around I realize that the delegate is an artifact from the TypedFactoryFacility. There seems to have been some change so it now resolves by type only. In older Castle versions the string argument was used to select component by name.
A factory would to the trick.
You need to add the FactorySupportFacility to your container for this to work.
For much more detail, see the Castle Windsor documentation at http://docs.castleproject.org/Default.aspx?Page=Factory-Support-Facility&NS=Windsor&AspxAutoDetectCookieSupport=1.
See also http://www.mail-archive.com/castle-project-users#googlegroups.com/msg04463.html.
DependsOn does work for other things than statics, the problem is that the injected delegate does not resolve the way it used to. I ended up registering my own component for handling this specific delegate
container.Register(Component.for<Func<ISession,string>>().ImplementedBy(sessionName => container.resolve<ISession>(sessionName));
(I typed the above from memory so please excuse any typos)

Looking for way to replace many "when...thenReturn" statements in test method

I'm writing a JUnit test on a method that is interacting primarily with classes in org.apache.poi.hssf.usermodel (like HSSFWorkbook, HSSFFont and HSSFCellStyle).
The method ultimately builds up and returns an HSSFWorkbook object.
In order to build up the HSSFWorkbook object, methods like workbook.createFont() and workbook.createCellStyle() are invoked.
I currently mock out the objects like this in the setup class of my unit test
workbook = mock(HSSFWorkbook.class);
font = mock(HSSFFont.class);
cellStyle = mock(HSSFCellStyle.class);
Then, in my test method, I invoke the following to avoid NPEs
when(workbook.createFont()).thenReturn(font);
when(workbook.createCellStyle()).thenReturn(cellStyle);
I'm discovering I'll have to do many more of those in order to avoid the NPEs and I'm wondering if there's a way that I can avoid writing all of those "when...thenReturn" statements.
one of the rules of Mocking is: Never mock types you don't own. Another rule is a stubbed call on a mock, shouldn't return another mock.
The reason is in front of you :).
If your class only deals with creating the HSSFWorkbook, then treat the tests as integration tests and use the real library. If your class does something else too, then move all the other stuff to other classes (this is to follow the single responsibility principle)

Castle Dynamic Proxy in Windsor Container

I've got a bit of a problem. I'm working in the Castle Windsor IOC Container. Now what i wanted to do is just mess about with some AOP principles and what i specifically want to do is based on a method name perform some logging. I have been looking at Interceptors and at the moment i am using the IInterceptor interface implemented as a class to perform this logging using aspects. The issue is if i want to perform the logging on a specific method then it gets messy as i need to put in some logic into my implemented aspect to check the method name etc...
I have read that you can do all of this using Dynamic Proxies and the IInterceptorSelector interface and the IProxyGenerationHook interface. I have seen a few examples of this done on the net but i am quite confused how this all fits into the Windsor container. I mean i am using the windsor container which in my code is actually a ref to the IWindsorContainer interface to create all my objects. All my configuration is done in code rather than XML.
Firstly does anyone know of a way to perform method specific AOP in the windsor container besides the way i am currently doing it.
Secondly how do i use the Dynamic Proxy in the windsor container ?
Below i have added the code where i am creating my proxy and registering my class with
the interceptors
ProxyGenerator _generator = new ProxyGenerator(new PersistentProxyBuilder());
IInterceptorSelector _selector = new CheckLoggingSelector();
var loggingAspect = new LoggingAspect();
var options = new ProxyGenerationOptions(new LoggingProxyGenerationHook())
{ Selector = _selector };
var proxy = _generator.CreateClassProxy(typeof(TestClass), options, loggingAspect);
TestClass testProxy = proxy as TestClass;
windsorContainer.Register(
Component.For<LoggingAspect>(),
Component.For<CheckLoggingAspect>(),
Component.For<ExceptionCatchAspect>(),
Component.For<ITestClass>()
.ImplementedBy<TestClass>()
.Named("ATestClass")
.Parameters(Parameter.ForKey("Name").Eq("Testing"))
.Proxy.MixIns(testProxy));
The Test Class is below:
public class TestClass : ITestClass
{
public TestClass()
{
}
public string Name
{
get;
set;
}
public void Checkin()
{
Name = "Checked In";
}
}
as for the interceptors they are very simple and just enter a method if the name starts with Check.
Now when i resolve my TestClass from the container i get an error.
{"This is a DynamicProxy2 error: Mixin type TestClassProxy implements IProxyTargetAccessor which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to mix in an existing proxy?"}
I know i'm using the proxy in the wrong way but as i haven't seen any concrete example in how to use a proxy with the windsor container it's kind of confusing.
I mean if i want to use the LoggingProxyGenerationHook which just tell the interceptors to first for methods that start with the word "check" then is this the correct way to do it or am i completely on the wrong path. I just went down the proxy way as it seems very powerfull and i would like to understand how to use these proxies for future programming efforts.
By using .Interceptors() you already are using Dynamic Proxy. When component has specified interceptors Windsor will create proxy for it, and use these interceptors for it. You can also use method .SelectedWith and .Proxy property to set other options you already know from DynamicProxy.
I just added a website about Windsor AOP to documentation wiki. There's not much there yet, but I (and Mauricio ;) ) will put there all the information you need. Take a look, and let us know if everything is clear, and if something is missing.

How to pass arguments to a constructor in an IOC-framework

How can I pass arguments to a constructor in an IOC-framework?
I want to do something like: (Trying to be IOC-framework agnostic ;) )
object objectToLogFor = xxx;
container.Resolve<ILogging>(objectToLogFor);
public class MyLogging : ILogging
{
public MyLogging(object objectToLogFor){}
}
It seems that this is not possible in StructureMap. But I would love to see someone prove me wrong.
Are other frameworks more feature-rich? Or am I using the IOC-framework in the wrong way?
In structure map you could achieve this using the With method:
string objectToLogFor = "PolicyName";
ObjectFactory.With<string>(objectToLogFor).GetInstance<ILogging>();
See: http://codebetter.com/blogs/jeremy.miller/archive/2008/09/25/using-structuremap-2-5-to-inject-your-entity-objects-into-services.aspx
For Castle Windsor:
var foo = "foo";
var service = this.container.Resolve<TContract>(new { constructorArg1 = foo });
note the use of an anonymous object to specify constructor arguments.
using StructureMap:
var foo = "foo";
var service = container.With(foo).GetInstance<TContract>();
How can this be language-agnostic? This is implementation detail of the framework in question.
Spring alows you to specify c'tor args as a list of values/references, if that's your thing. It's not very readable, though, compared to property injection.
Some people get hot under the collar about this, and insist that c'tor injection is the only thread-safe approach in java. Technically they're correct, but in practice it tends not to matter.
It should not be a very common need, but sometimes it is a valid one. Ninject, which is lighter than StructureMap, allows you to pass parameters when retrieving transient objects from the context. Spring.NET too.
Most of the time, objects declared in an IoC container aren't transient, and accept others non-transient objects through constructors/properties/methods as dependencies.
However, if you really wan't to use the container as a factory, and if you have enough control on the objects you want to resolve, you could use property or method injection even if it sounds less natural and more risky in some way.
Yes, other frameworks are more feature-rich - you need to use an ioc framework that allows for constructor injection. Spring is an example of a multi-language ioc container that allows constructor dependency injection.
Other IoC frameworks are more feature rich.
I.e. check out the ParameterResolution with Autofac
You can also do that with Windsor easily