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
Related
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();
}
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.
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.
I'm preparing a presentation of Guice, where I plan to demonstrate the (correct) behaviour of Guice by executing Unit Tests. In the following test case, I want to ensure that the correct types were injected
#Test
public void shouldInjectCorrectDependencies() {
Injector injector = Guice.createInjector(new ModuleImpl());
House house = injector.getInstance(House.class);
Assert.assertTrue(house.door().getClass() == (WoodenDoor.class));
}
Now, I wonder which approach would be better:
Using getClass() to check for a concrete class
Using instanceof to check for a type (and subtypes)
I no expert on Guice, but in Spring DI, you can have instances injected which are not instances of the class you're expecting. For instance, in your example, if House is not a class, but an interface, then spring under certain circumstances (for instance if you're using a transaction) gives you a Proxy, not an instance of a class which implements the interface. The only guarantee you have is that it will implement the correct interface. So I would use:
Assert.assertTrue(house.door().isAssignableFrom(WoodenDoor.class));
Instead of reasoning with classes, which is error prone as pointed out by Matthew, why not have the correct class implement a method which, when called, returns the result you expect?
In this case, maybe:
public class Door {
public String getDescription() { return "Wood"; }
}
...
Injector injector = Guice.createInjector(new ModuleImpl());
Assert.assertEquals("Wood", injector.getInstance(House.class).door().getDescription());
Disclaimer
Please don't just vote to close this because the title looks subjective, and if it's been asked before please point me to the previous question in the comments and I'll delete this one -- I really did look high and low trying to find a previous question on the subject.
Background
Given I have the following interface and concrete implementation:
public interface IFoo
{
// Some stuff
}
public class Foo : IFoo
{
// Concrete implementations of stuff
}
And somewhere I have the following method:
public Foo GiveMeAFoo()
{
return new Foo();
}
I have traditionally always returned Foo, seeing as it is inherently an IFoo anyway, so it can be consumed at the other end as an IFoo:
IFoo foo = GiveMeAFoo();
The main advantage of this that I can see is that if I really need to consume Foo somewhere as the concrete implementation, I can.
Actual Question
I recently came across some comments on another question, giving someone a hard time for doing this, suggesting the return type should be IFoo.
Am I wrong or are they? Can anyone give me a reason why returning the concrete implementation is a bad idea?
I know that it makes sense to require an IFoo when receiving a parameter to a method, because the less specific a parameter is, the more useful a method is, but surely making the return type specific is unreasonably restrictive.
Edit
The use of IFoo and Foo might have been too vague. Here's a specific example from .NET (in .NET, arrays implement IEnumerable -- i.e. string[] : IEnumerable<string>)
public string[] GetMeSomeStrings()
{
return new string[] { "first", "second", "third" };
}
Surely it's a bad idea to return IEnumerable here? To get the length property you'd now have to call Enumerable.Count(). I'm not sure about how much is optimised in the background here, but logic would suggest that it's now going to have to count the items by enumerating them, which has got to be bad for performance. If I just return the array as an array, then it's a straight property lookup.
If you want your method to be the most flexible that it can be, you should return the least derived type (in your case, IFoo):
public interface IFoo { }
public class Foo : IFoo { }
public IFoo GiveMeAFoo() { return new Foo(); }
That will allow you to change the concrete implementation of IFoo internal to your method without breaking anybody that is consuming your method:
public interface IFoo { }
public class Foo : IFoo { }
public class Foo2 : IFoo { }
public IFoo GiveMeAFoo() { return new Foo2(); }
You can create a bunch of interfaces and give it to different teams. Taking your own example
public interface IFoo
{
// Some stuff
}
public interface IBar
{
public IFoo getMeAFoo();
}
Then you can give these interfaces to a person developing a front end app and he doesn't have to know what the concrete implementation is. The guy developing the front end can use the getMeAFoo() method knowing that it returns an object of IFoo whereas the concrete implementation can be developed separately as:
public class Foo implements IFoo
{
// more stuff
}
public class MoreFoo implements IFoo
{
//
}
public class WunderBar implements IBar
{
public IFoo getMeAFoo()
{
case 1:
return new Foo();
case 2:
return new MoreFoo();
}
}
Hope this makes sense :)
In my opinion, it's always better to return the most abstract type you can. If you find yourself in need for anything that's specific to the type you ar actually returning, I would consider it a code smell.
The main advantage of this is that you can change your mind about which type you really want to return. The called method is made more decoupled from its callers.
Also, you can possibly remove dependencies. The caller code don't need to know anything about the actual type you chose to create.
My final remark is a quotation from Eric Lippert: "You probably should not return an array as the value of a public method or property". (His article is focused in C#, but the general idea is language-agnostic)
Fine, everywhere you use it, you use IFoo foo = GiveMeAFoo();
Then someone else uses your code and doesn't use it that way, for whatever reason, they use Foo foo = GiveMeAFoo();
Now they see all the functionality of Foo that isn't (for good reason) part of IFoo. Now they can use parts of the implementation that aren't part of the interface. Now you can't change your implementation without breaking their code, your implementation is now the public API and you are going to tick people off if you try to change your implementation details that they are counting on.
Not good.