Windsor Dependency Injection Problem with generics - castle-windsor

I have an Interface IRepo <Entity>. I have a generic implementation Repo<Entity>.
Now i just do the following
Container.Register(AllTypes.FromAssemblyNamed("assemblyname").Pick()
.WithService.DefaultInterface()
.Configure(c => c.LifeStyle.PerWebRequest))
and register all the interface with respective implementations. This seems to work fine.
My Problem arises when i try to be more specific.
If i try to map IRepo<Person> with Person being a class subclassing Entity with <UserRepo> using
Container.Register(Component.For(IRepo<Person>).ImplementedBy(UserRepo).LifeStyle.PerWebRequest);
It does not seem to work.
The order in which i am doing this is that i am registering this specific implementation and then loading and registering all the interfaces to types from the assembly.
It does not seem to work.

DefaultInterface doesn't support generics. You can use AllInterfaces instead or a custom strategy via Select method

Related

UploadedFile Junit Primefaces

Is there are any way to instantiate an object of UploadedFile without using Mockito?
I've been searching but I only have found examples using Mockito. I'm trying to do Junits and I would like to avoid using it.
Thanks!
It is an interface, so if you don't want to use Mockito (or a similar mocking tool) just create your own class and implement the interface explicitly. There are not that many methods, so it is straightforward.
EDIT: or just use the public constructor in DefaultUploadedFile and go with that implementation.

Class loading collision between Robolectric and Powermock

I'm trying to write a test that needs both Robolectric 2.2 and PowerMock, as the code under test depends on some Android libraries and third party libraries with final classes that I need to mock.
Given that I'm forced to use the Robolectric test runner through:
#RunWith(RobolectricTestRunner.class)
...I cannot use the PowerMock test runner, so I'm trying to go with the PowerMock java agent alternative, without luck so far.
I have setup everything according to this guide but I'm facing a collision problem between classes required by the javaagent library and by robolectric through its dependency with asm-1.4. Both depend on
org.objectweb.asm.ClassVisitor
, but javaagent-1.5.1 ships with its own version where ClassVisitor is an interface while asm-1.4 version for the same namespace is an abstract class, with the corresponding error at runtime:
java.lang.IncompatibleClassChangeError: class org.objectweb.asm.tree.ClassNode has interface org.objectweb.asm.ClassVisitor as super class
I have even tried to modify the javaagent library jar to entirely remove the org.objectew.asm classes in there, but that doesn't work as ClassNotFoundException happens afterwards due to some other classes needed in the org.objectweb.asm package that only ship in the javaagent library jar, and not in the asm one.
Any ideas? According to examples out there the agent seems to work fine with, at least, the Spring test runner.
I had the same problem and while I didn't solve this problem as such, I wanted to share my approach, which removes the need for PowerMock (which is always a good thing in my view): I wanted to mock a call to
Fragment fooFragment = new FooFragment();
So what I did was addanother level of indirection. I created a FragmentProvider class:
public FragmentFactory fragmentFactory = new FragmentFactory();
[...]
Fragment fooFragment = fragmentFactory.getFooFragment();
After i did this, I could just mock out the factory with standard Mockito, like this:
FragmentFactory mockFactory = mock(FragmentFactory.class);
activity.fragmentFactory = mockFactory;
when(mockFactory.getFooFragment()).thenReturn(mockFooFragment);

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)

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

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.

Can you add a dependency to a Castle component that was auto-registered?

I generally use StructureMap, but on a current project I'm using Castle Windsor (2.1). I've found some code to auto-register types and interfaces:
_container.Register(AllTypes.Pick().FromAssembly(GetType().Assembly).WithService.FirstInterface());
However I would like to add a string dependency to one of the types. I can do this without the convention like this:
var registration = Component.For() .ImplementedBy().DependsOn(new[] { Property.ForKey("someString").Eq("blahblah") });
_container.Register(registration);
Is there any way I can do this with the auto-registered types?
you use ConfigureFor<> method which lets you finetune your registration on a granular level.