Castle Windsor Resolve method: why pass arguments? What are they for? - castle-windsor

I am confused by Castle Windsor resolve method. This method allows me to pass almost anything. Is the value submitted in the resolve method passed along and used in the constructor of the object which is eventually resolved to, or is this value used to help the resolver determine what concrete implementation to use?
For example, if I have the following snippet...
var _container = new WindsorContainer();
_container.Install(FromAssembly.This());
var MyProcessor = _container.Resolve<IProcessor>(new Arguments(new {"Processor1"}));
assuming I have two concrete implementations of IProcessor - like Processor1:IProcessor, and/or Processor2:IProcessor. What are the 'Arguments' used for?
I understand the...
Component.For<IProcessor>()
... needs to be defined, but I am struggling with the terms the Windsor folks choose to use (i.e. DependsOn, or ServicesOverrides) and the intent. Given the method is called 'resolve' I can only image any values passed to this will be used to resolve the decision on which concrete implementation to use. Is this assumption wrong?

The arguments parameter you're talking about is for providing arguments to components that can't be satisfied by Windsor components. The anonymous types overloads as well as the dictionary overalls I believe are all for this purpose. I've used this in the past, and I don't recommend it as it leads to poor patterns like Cristiano mentioned... and last time I used this it only works for the component being directly resolved. Anyway... here's an example of how this works:
[TestFixture]
public class Fixture
{
[Test]
public void Test()
{
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IFoo>().ImplementedBy<Foo>().LifeStyle.Is(LifestyleType.Transient));
Assert.Throws<HandlerException>(() => container.Resolve<IFoo>());
IFoo foo = container.Resolve<IFoo>(new {arg1 = "hello", arg2 = "world"});
Assert.That(foo, Is.InstanceOf<Foo>());
Assert.That(foo.ToString(), Is.EqualTo("hello world"));
}
}
public interface IFoo
{
}
public class Foo : IFoo
{
private readonly string _arg1;
private readonly string _arg2;
public Foo(string arg1, string arg2)
{
_arg1 = arg1;
_arg2 = arg2;
}
public override string ToString()
{
return string.Format("{0} {1}", _arg1, _arg2);
}
}

I am awarding the answer to kellyb for the awesome example. During investigation, using Castle.Windsor 3.2.1, I found at least 2 reasons for passing a value in the "resolve" method.
To satisfy intrinsic type dependencies, such as strings, or integers in
the object resolved by the use of the "Resolve" method - as
described in kellyb's example.
To help Castle identify which concrete implementation to select.
to help illustrate both uses I am elaborating on the example provided above by kellyb.
Synopsis - or test condition
Assume there is one interface called IFoo and two concrete implementations that derive from this interface called Foo and Bar. A class called Baz is defined but does not derive from anything. Assume Foo requires two strings, but Bar requires a Baz.
Interface IFoo Definition
namespace CastleTest
{
public interface IFoo
{
}
}
Class Foo Definition
namespace CastleTest
{
public class Foo : IFoo
{
private readonly string _arg1;
private readonly string _arg2;
public Foo(string arg1, string arg2)
{
_arg1 = arg1;
_arg2 = arg2;
}
public override string ToString()
{
return string.Format("{0} {1}", _arg1, _arg2);
}
}
}
Class Bar Definition
namespace CastleTest
{
class Bar : IFoo
{
private Baz baz;
public Bar(Baz baz)
{
this.baz = baz;
}
public override string ToString()
{
return string.Format("I am Bar. Baz = {0}", baz);
}
}
}
Class Baz Definition
namespace CastleTest
{
public class Baz
{
public override string ToString()
{
return "I am baz.";
}
}
}
The Test (Drum roll, please!)
kellyb's example test shows an assert that expects a failure if args is not supplied. kellyb's example does not have multiple implementations registered. My example has multiple implementations registered, and depending on which is marked as the default this assert may or may not fail. For example, if the concrete implementation named "AFooNamedFoo" is marked as default, the assert completes successfully - that is to say the resolution of an IFoo as a Foo does indeed require args to be defined. If the concrete implementation named "AFooNamedBar" is marked as default, the assertion fails - that is to say the resolution of an IFoo as a Bar does not require args to be defined because its dependency of a Baz is already registered (in my example where multiple concrete implementations are registered). For this reason, I have commented out the assert in my example.
using Castle.Core;
using Castle.MicroKernel.Handlers;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using NUnit.Framework;
namespace CastleTest
{
[TestFixture]
public class ArgsIdentifyConcreteImplementation
{
[Test]
public void WhenSendingArgsInResolveMethodTheyAreUsedToIdentifyConcreteImplementation()
{
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IFoo>().ImplementedBy<Foo>().LifeStyle.Is(LifestyleType.Transient).Named("AFooNamedFoo"));
container.Register(Component.For<IFoo>().ImplementedBy<Bar>().LifeStyle.Is(LifestyleType.Transient).Named("AFooNamedBar").IsDefault());
container.Register(Component.For<Baz>().ImplementedBy<Baz>().LifeStyle.Is(LifestyleType.Transient));
// THIS ASSERT FAILS IF AFooNamedBar IS DEFAULT, BUT
// WORKS IF AFooNamedFoo IS DEFAULT
//Assert.Throws<HandlerException>(() => container.Resolve<IFoo>());
// RESOLVE A FOO
IFoo foo = container.Resolve<IFoo>("AFooNamedFoo", new { arg1 = "hello", arg2 = "world" });
Assert.That(foo, Is.InstanceOf<Foo>());
Assert.That(foo.ToString(), Is.EqualTo("hello world"));
// RESOLVE A BAR
IFoo bar = container.Resolve<IFoo>("AFooNamedBar");
Assert.That(bar, Is.InstanceOf<Bar>());
Assert.That(bar.ToString(), Is.EqualTo("I am Bar. Baz = I am baz."));
}
}
}
Conclusion
Looking at the test above, the resolution of a Foo object has two things passed in the "resolve" method - the name of the implementation, and the additional string dependencies as an IDictionary object. The resolution of a Bar object has one thing passed in the "resolve" method - the name of the implementation.

In fact you should not call Resolve ever in your code rather than in the Composition root and also there you should not need to supply parameters to the Resolve method.
Custom resolution strategies should be done through installers, factories/ITypedFactoryComponentSelector, subresolvers... see documentation for more details on those options
BTW through "Resolve" parameters you can identify the component to resolve(by name or type) and its own direct dependencies.

Related

Any alternative to injecting Castle Windsor typed factories?

Most of my components are registered using the code-based (fluent) approach, but there is one particular component that I need to resolve differently at runtime. This is the interface and a couple of concrete implementations:-
public interface ICommsService ...
public class SerialCommsService : ICommsService ...
public class TcpCommsService : ICommsService ...
Some of our users will need the serial service while others will need the TCP service. My current solution (which works btw) is to use a typed factory and a custom component selector - the latter reads an app.config setting to determine which implementation the typed factory will resolve and return.
First the typed factory (nothing special about this):-
public interface ICommsServiceFactory
{
ICommsService Create();
void Release(ICommsService component);
}
Next, the custom component selector, which reads the fully-qualified type name from app.config (e.g. "MyApp.SomeNamespace.TcpCommsService"):-
public class CommsFactoryComponentSelector : DefaultTypedFactoryComponentSelector
{
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
return ConfigurationManager.AppSettings["commsServiceType"];
}
}
Then the registration stuff:-
var container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<ITypedFactoryComponentSelector>()
.ImplementedBy<CommsFactoryComponentSelector>());
container.Register(Component.For<ICommsFactory>()
.AsFactory(o => o.SelectedWith<CommsFactoryComponentSelector>()));
container.Register(Component.For<ICommsService>()
.ImplementedBy<SerialCommsService>().LifeStyle.Singleton);
container.Register(Component.For<ICommsService>()
.ImplementedBy<TcpCommsService>().LifeStyle.Singleton);
Finally, an example class with a dependency on ICommsService:-
public class Test
{
public Test(ICommsFactory commsFactory)
{
var commsService = commsFactory.Create();
...
}
}
As already mentioned, the above solution does work, but I don't like having to inject the factory. It would be more intuitive if I could just inject an ICommsService, and let something somewhere figure out which implementation to resolve and inject - similar to what I'm doing now but earlier in Windsor's "resolving pipeline". Is something like that possible?
You can use UsingFactoryMethod here:
container.Register(Component.For<ICommsService>().UsingFactoryMethod(kernel => kernel.Resolve<ICommsServiceFactory>().Create()));
You can inject ICommsService to any class now. ICommsServiceFactory can be a simple interface now:
interface ICommsServiceFactory
{
ICommsService Create();
}

How to check that a List contains only certain unrelated class types using junit's assertThat?

Would appreciate some help with hamcrest and junit matchers... :)
I'm using junit-4.11.jar and hamcrest-core-1.3.jar on Eclipse Kepler with sun's jdk 1.6.0_30.
I have a class that holds an instance of any unknown type like so:
class UnknownClassHolder {
private Class<?> clazz;
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
}
clazz can be any class.
I want to my junit test to be something like this:
class UnknownClassHolderTest {
#Test
public void test() {
ArrayList<UnknownClassHolder> list = new ArrayList<UnknownClassHolder>();
UnknownClassHolder x = new UnknownClassHolder();
//lets add an Integer
x.setClazz(Integer.class);
list.add(x);
UnknownClassHolder y = new UnknownClassHolder();
//lets add a vector
y.setClazz(Vector.class);
list.add(y);
//now check that we added an Integer or a Vector using assertThat
for (UnknownClassHolder u: list) {
assertThat(u.getClazz(), anyOf(isA(Integer.class), isA(Vector.class))));
}
}
}
Junit's assertThat doesn't like this. It doesn't compile due to Integer & Vector Types not being related to each other via sub/super classes:
The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Class<capture#1-of ?>, AnyOf<Vector>)
Is there a more succinct way to do this other than:
assertThat(u.getClazz().getName(), either(is(Integer.class.getName())).or(is(Vector.class.getName())));
Is there a particular reason for using Matcher<? super T> rather than Matcher<?> in the org.hamcrest.MatcherAssert.assertThat(...) method?
Thanks.
First, you should be using is instead of isA since you're asserting that one class equals another. isA is for testing that an object is an instance of some class. Second, the only thing I can make work is forcing the compiler to see these as raw Objects.
assertThat(u.getClazz(), anyOf(is((Object) Integer.class), is((Object) Vector.class)));

Intercepting the concrete implementation (as opposed to service) using Castle Windsor

I'm experimenting with interception in Castle Windsor and notice that interceptors seem to be created as decorators of my service interface.
In other words, if I have an interface "ISomethingDoer" and a concrete "ConcreteSomethingDoer", the proxy implements ISomethingDoer but does not inherit from ConcreteSomethingDoer.
This is fine, and no doubt by design, but what I'm wondering is whether I can intercept protected virtual methods in my concrete classes that wouldn't be known by the public interface. I am doing this in order to add logging support, but I might want to log some of the specific internal details of a class.
In my slightly unimaginative test case I have this:
public interface ISomethingDoer
{
void DoSomething(int Count);
}
[Loggable]
public class ConcreteSomethingDoer : ISomethingDoer
{
public void DoSomething(int Count)
{
for (var A = 0; A < Count; A++)
{
DoThisThing(A);
}
}
[Loggable]
protected virtual void DoThisThing(int A)
{
("Doing a thing with " + A.ToString()).Dump();
}
}
So what I want to do is log calls to "DoThisThing" even though it's not part of the interface.
I've managed to get this working in Autofac. (I've created a Linqpad script here: http://share.linqpad.net/frn5a2.linq) but am struggling with Castle Windsor (see http://share.linqpad.net/wn7877.linq)
In both cases my interceptor is the same and looks like this:
public class Logger : IInterceptor
{
public void Intercept(IInvocation Invocation)
{
String.Format("Calling method {0} on type {1} with parameters {2}",
Invocation.Method.Name,
Invocation.InvocationTarget.GetType().Name,
String.Join(", ", Invocation.Arguments.Select(a => (a ?? "*null*").ToString()).ToArray())).Dump();
Invocation.Proceed();
"Done".Dump();
}
}
What I really want to do is say "any classes with a [Loggable] attribute, should use the logging interceptor". In the Autofac example I've specifically attached a logger to the registration, whereas with Castle I'm using an IModelInterceptorsSelector which looks like this:
public class LoggerInterceptorSelector : IModelInterceptorsSelector
{
public bool HasInterceptors(ComponentModel Model)
{
return Model.Implementation.IsDefined(typeof(LoggableAttribute), true);
}
public InterceptorReference[] SelectInterceptors(ComponentModel Model, InterceptorReference[] Interceptors)
{
return new[]
{
InterceptorReference.ForType<Logger>()
};
}
}
Finally, the code to execute all this is:
var Container = new WindsorContainer();
Container.Register(
Component.For<Logger>().LifeStyle.Transient
);
Container.Kernel.ProxyFactory.AddInterceptorSelector(new LoggerInterceptorSelector());
Container.Register(
Component.For<ISomethingDoer>()
.ImplementedBy<ConcreteSomethingDoer>()
.LifeStyle.Transient
);
var Doer = Container.Resolve<ISomethingDoer>();
Doer.DoSomething(5);
When run I would expect to see "Calling method DoThisThing with parameters x" for each time the method is called. Instead I only get the call to DoSomething logged.
I can see why Castle Windsor is doing this, but I'm wondering if there is a way to tweak the behaviour?
(As a side-note I don't want to use Windsor's own interceptor attributes as I don't want to introduce dependencies to Castle outside of my composition root.)
I have tried resolving the ConcreteSomethingDoer specifically and this works, but not if I'm resolving the ISomethingDoer.
Apologies for the long post, and also apologies because I am pretty new to Castle Windsor!
I you could register like:
Container.Register(
Component.For<ISomethingDoer, ConcreteSomethingDoer>()
.ImplementedBy<ConcreteSomethingDoer>()
.LifeStyle.Transient
);
This should create a class proxy by deriving from ConcreteSomethingDoer. However this won't work with dynamic interceptors. However you probably can work around that by creating a facility which registers the interceptor when needed.

feeding dependencies to a factory class via IoC?

I have a factory class that decides which of four available subclasses it should instantiate and return. As you would expect, all subclasses implement the same interface:
public static class FooFactory{
public IFoo CreateFoo(FooEnum enum){
switch (enum)
{
case Foo1:
return new Foo1();
case Foo2:
return new Foo2();
case Foo3:
return new Foo3(IBar);//has a constructor dependency on IBar
case Foo4:
return new Foo4();
default:
throw new Exception("invalid foo!");
}
}
}
As you can see, one of the subclasses has a dependency defined in its constructor.
Some points of interest:
We're using Spring.NET as our IoC.
All subclasses of IFoo are domain objects and therefore are not being instantiated by Spring.NET. I'd like to keep things this way if at all possible.
The application has a hand written Data Access Layer (puke) so no ORM is in play here.
I'm trying to figure out how best to pass the IBar dependency into Foo3 from FooFactory. I get the feeling that this might be a problem best resolved via IoC but I can't quite grok how. I also want to keep FooFactory as unit testable as possible: i.e. I'd prefer not have to have dependencies on Spring.NET in my test code.
Thanks for reading.
Change FooFactory to an Abstract Factory and inject the IBar instance into the concrete implementation, like this:
public class FooFactory : IFooFactory {
private readonly IBar bar;
public FooFactory(IBar bar)
{
if (bar == null)
{
throw new ArgumentNullException("bar");
}
this.bar = bar;
}
public IFoo CreateFoo(FooEnum enum){
switch (enum)
{
case Foo1:
return new Foo1();
case Foo2:
return new Foo2();
case Foo3:
return new Foo3(this.bar);
case Foo4:
return new Foo4();
default:
throw new Exception("invalid foo!");
}
}
}
Notice that FooFactory is now a concrete, non-static class implementing the IFooFactory interface:
public interface IFooFactory
{
IFoo CreateFoo(FooEnum emum);
}
Everywhere in your code where you need an IFoo instance, you will then take a dependency on IFooFactory and use its CreateFoo method to create the instance you need.
You can wire up FooFactory and its dependencies using any DI Container worth its salt.
sounds like you want your cake and to eat it too. you need to commit to your IOC strategy.
you will produce mo an betta code and the chicks will dig you more too.... ;p

Should a class ever have static and non-static members

I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.