Choosing the correct constructor using an external configuration file in Windsor? - castle-windsor

I'm new to Windsor, but I'm certain there must be a way to do this...
I have a class with three different constructors:
public MyClass(string SomeParam)
{
...
}
public MyClass(string AnotherParam, string YetAnother)
{
...
}
public MyClass(string AnotherOne, string YeahIKnow, string AnnoyingExampleParam)
{
...
}
In my external configuration file, I have my service defined as:
<component
id="IMyClass"
service="IMyInterface, MyAssembly"
type="MyClass, MyOtherAssembly">
<parameters>
<AnotherOne>string value #1</AnotherOne>
<YeahIKnow>string value #2</YeahIKnow>
<AnnoyingExampleParam>string value #3</AnnoyingExampleParam>
</parameters>
</component>
When Windsor initializes an instance of my class, it only wants to initialize using the first (single string parameter) constuctor of my class, when I really want Windsor to use the third constructor.
I don't see anything in the docs about forcing the kernel to us a particular constructor using an external configuration, even though I can find references to doing it in code, but that sort of defeats the purpose of an external configuration!
Any advice would be appreciated.
Best,
David Montgomery

What version of Castle? I recall, from the depths of what goes for my memory at 4am in the morning, that there was a resolution for constructor work in Castle 2.0.
Humm, memory coming back a little now... Something tells me that Castle will construct the object with the first public ctor. May be as simple as moving what you want for Castle to load, to the top.
If that doesn't work for you, perhaps refactor your code a little?
Option 1) Make the first two constructors internal.
Option 2) Use a Factory pattern for your complex objects, which will utilize castle on the backend to new up the more simple or complex version.
Option 3) Create 3 classes from your base superclass, each having a more complicated constructor. This way, you can specific in the Castle config file exactly which service to load. For example:
public abstract class BaseClass
{
public BaseClass(String requiredParam)
{
...
}
}
public class SimpleClass : BaseClass
{
public SimpleClass(String requiredParam, String anotherParam)
: base(requiredParam)
{
...
}
}
public class MoreComplexClass : SimpleClass
{
public MoreComplexClass (String requiredParam, String anotherParam, String yetAnother)
: base(requiredParam, anotherParam)
{
...
}
}
But, I myself have not run into this yet. Mainly because I stick to only public 1 ctor on my classes, with a few private/internal ctors for things such as Linq to new up my objects with an empty ctor (since Linq doesn't support Dependency Injection, boo).
Note that in that last statement, internal ctors, that my SRP (Single Responsiblity Pattern) for resolving my IoC components is external, in a seperate higharchy assembly (i.e. an application or UI layer). Since it not internal to my domain objects, the internal ctors are not seen by Castle.

You must be doing something wrong.
Windsor uses the greediest constructor it can satisfy. If it uses the smaller one, you perhaps have some typo?
when your type is the service, you don't have to specify both
service="MyClass, MyAssembly"
type="MyClass">
remove the type.

Related

how to add annotations to method/constructor parameters without touching the source code?

I am trying to de/seralize framework objects (no source code access) into JSON using jackson 2.
class Item {
public Item(Long id) {}
}
I found this Add annotation to a parameter on a new method created with Javassist but this solution is based on JavaAssist and does not fully apply :(
The underlying issue is the lack of DefaultConstructors which can be solved using the #JsonCreator annotation together with a matching #JsonProperty annotation for the parameter.
#JsonCreator
class Item {
public Item(#JsonProperty("id") Long id) {}
}
I managed to achieve this for one of the many item subclasses using a mixin class.
public abstract class ItemChildMixin {
#JsonCreator
public ItemChildMixin(#JsonProperty("objId") final Long objId) {
}
}
However, writing mixin classes for all the relevant objects with almost the same content seems the wrong approach, so I started looking at aspects.
Adding the Annotation to the classes in the Item's hierarchy was easy:
aspect DeclareJsonCreatorAspect {
declare #constructor: Item+.new(Long): #JsonCreator;
}
However, I cannot seem to find a way to add an annotation to the constructor parameters using Aspects!
Aspectj in Action as well as google did not provide an answer yet.
Is this at all possible?
Currently AFAIK AspectJ (currently v1.8.4) is unable to deal with annotations on method parameters, be it in pointcuts or in ITD (inter-type definition) statements.
I am sorry that I do not have any better news, but this is the status quo. If you have a chance to declare whole methods via ITD you can influence the full signature, but adding parameter annotations on existing methods is impossible today. You might also be able to also declare default constructors via ITD, if that helps. I am pretty sure there is a way to achieve what you want, just maybe not the way you imagine.

MVC3 ImportMany on Constructor Parameter for Exported Controller

I have a controller that is exported using MEF and loaded by the Controller factory.
[Export(Controller)]
public class MyController : Controller
{
private IRepository MyRepsoitory;
[ImportMany]
public IEnumerable<MyImportedItem> TestImportItems {get;set;}
public MyController([ImportMany]IEnumberable<MyImportedItem> items, [Import]IRepository repository)
{
// items here is always null
// However if I grab the container that the ControllerFactory used and tell it ComposeParts on this the TestImportItems will be filled with 50+ items
// repository however is instantiated appropriately.
GlobalItems.Container.ComposeParts(this);
//Now TestImportItems if filled but my items parameter alway null... how do I get constructor to fill
}
}
So MEF creates MyController but only creates the repository and sends null for the ImportMany even though it can fill the property later with the same Container.
What's also odd is if I do something that breaks one of the items the creation of MyConroller breaks in ControllerFactory.. as if it checks that is has parts for the constructor but never pushes them to the IEnumerable parameter.
What am I missing?
Obviously I have the parts available if the same Container works for .ComposingParts on (this) (and I reflected the catalog which has appropriate import/export Parts available at time of creating the Controller.
I could rewrite my class to use the filled Property but I would really like my importing constructor to get a filled collection.
UPDATE:
If I add a simple wrapper class for the import many MEF will load the [ImportMany] parameter.
So the following will fill the IEnumerable for me...
public MyController(TestImportClass test, [Import]IRepository repository)
{
//test.Items != null
}
public class TestImportClass
{
public IEnumberable<MyImportedItem> Items {get;set;}
[ImportingConstructor]
public TestImportClass([ImportMany]IEnumberable<MyImportedItem> items)
{
this.Items = items;
}
}
I am using a "Convention" system in my actual code to mark the Controller for Export. Maybe for some reason that is causing MEF to not understand the Import on initial Constructor Parameter? If that were the case though i am not sure why my IRepository always gets filled?
When you call ComposeParts, you pass objects which have already been constructed. It's not possible to call the constructor again on an existing object. (And in this case if you did you'd end up with infinite recursion). So ComposeParts doesn't satisfy constructor imports.
If your controller is pulled from the container some other way, and you put an ImportingConstructorAttribute on the constructor, the constructor imports should be satisfied.
Probably the convention system you are using doesn't support ImportMany in constructor arguments. Presumably the convention isn't applying to TestImportClass which is why the ImportMany works on that constructor.
We plan to have official convention model support in the next version of MEF, and we should be shipping a new codeplex release with a preview of this support soon.

Why can't an object of abstract class be created?

Here is a scenario in my mind and I have googled, Binged it a lot but got the answer like
"Abstract class has not implemented method so, we cant create the object"
"The word 'Abstract' instruct the compiler to not create an object of the class"
But in a simple class where we have all virtual method, able to create an object???
Also, we can define different access modified to Abstract class constructor like private, protected or public.
My search terminated to this question:
Why we can't create object of an Abstract class?
An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.
An abstract class has a protected constructor (by default) allowing derived types to initialize it.
For example, the base-type Stream is abstract. Without a derived type where would the data go? What would happen when you call an abstract method? There would be no actual implementation of the method to invoke.
Because it's abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.
Take for example an "Animal" abstract class. There's no such thing as a "pure" animal - there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn't be able to instantiate plain Animal - that's just a basic template. And there's certain functionality that all animals share, such as "makeSound()", but that can't be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?
It's intended to be used as a base class.
http://msdn.microsoft.com/en-us/library/sf985hc5(VS.71).aspx
The abstract modifier can be used with
classes, methods, properties,
indexers, and events.
Use the abstract modifier in a class
declaration to indicate that a class
is intended only to be a base class of
other classes.
Abstract classes have the following
features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Abstract classes should have at least one virtual method or property that has no implementation. This is marked with the abstract keyword. Inheriting classes must provide an implementation if they are not abstract themselves. You cannot create an instance of an abstract class because it does not have a complete implementation. If it does, it should not be marked abstract in the first place.
As an addition to the other answers, you may not be able to create an instance of the abstract class, but you can certainly refer to instances of derived types through the abstract type and use methods or properties that are defined within the abstract base.
abstract class A
{
public abstract void D();
public void E() { }
}
class B : A
{
public override void D() { }
}
class C : A
{
public override void D() { }
}
...
A a = new B();
a.D();
a.E();
List<A> list = new List<A>() { new B(), new C() };
Simply speaking, an abstract class is like a shell of a class. Not all the methods have implementations, something like a circuit with some wire segments missing. While the majority of it may be constructed, it is up to the users to stick in the wires and resistors in those segments as they see fit.
As to why Java won't let you create it, part of it is just a failsafe (many abstract classes will function just fine without any additions as long as you don't call unimplemented methods).
If we have a class containing pure virtual function then the class is abstract. If we will create an object of the abstract class and calls the method having no body(as the method is pure virtual) it will give an error. That is why we cant create object of abstract class.
We cannot create object for abstract class bcoz ,mostly abstract class contain "abstract methods" ,so abstract methods are incomplete methods.so we cannot estimate the memory of those methods how much they are going to occupy .This is one of the reason why we cannot create object for abstract class.
Here is a similar StackOverflow question. In short, it is legal to have a public constructor on an abstract class. Some tools will warn you that this makes no sense.
Whats the utility of public constructors in abstract classes in C#?
Actually when we create an object of a normal class we use Constructor to allocate the memory
for that object like
myclass obj=new myclass();
Here using constructorr clr identifies how much memory the object needed depending upon the instance variabless and methods. But in case of abstract classes we cant predict the amount of memory required as we dont implement the abstract methods so its not possible to create object.
When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.
Source : Study Tonight
The reference studytonight :
When we create a pure virtual function in Abstract class, we reserve a
slot for a function in the VTABLE(studied in last topic), but doesn't
put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler
will not let the creation of object for such class and will display an
errror message whenever you try to do so.
Sorry guys...
You can Create object for an abstract class, if and only if that abstract class does not contains any abstract method.
Here is my Example. Copy it and compile and run.
abstract class Example {
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo {
public static void main(String[] args) {
Example ob = new Example(){};
ob.display();
}
}
So your answer is yes, we can create object for abstract class if it's no Abstract Method.
Check my program.
I don't agree with the accepted answer. The reason is that we can have body for pure virtual function.
The answer is that :
When we create a pure virtual function in the class, we reserve a slot for a function in the VTABLE, but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an error message whenever you try to do so.
we can create object for abstract class like this also...
public class HelloWorld
{
public static void main(String args[])
{
Person p = new Person()
{
void eat()
{
console.writeline("sooper..");
}
};
p.eat();
}
}
abstract class Person
{
abstract void eat();
}
every body is writing dat abstract class has some virtual function which has not defined. for dat reason we cant create object, but abstract class is a class with the key word 'abstract' which may or may not have abstract method. i think it is a concept, it does not take any memory for dat. so if we can create an object den a memory will be created which is not possible, for dat reason we can't create object of an abstract class bt we can create reference of it which does not occupy any memory location.

Design pattern to use instead of multiple inheritance

Coming from a C++ background, Im used to multiple inheritance. I like the feeling of a shotgun squarely aimed at my foot. Nowadays, I work more in C# and Java, where you can only inherit one baseclass but implement any number of interfaces (did I get the terminology right?).
For example, lets consider two classes that implement a common interface but different (yet required) baseclasses:
public class TypeA : CustomButtonUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
public class TypeB : CustomTextUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
Both classes are UserControls so I cant substitute the base class. Both needs to implement the DoMagic function. My problem now is that both implementations of the function are identical. And I hate copy-and-paste code.
The (possible) solutions:
I naturally want TypeA and TypeB to share a common baseclass, where I can write that identical function definition just once. However, due to having the limit of just one baseclass, I cant find a place along the hierarchy where it fits.
One could also try to implement a sort of composite pattern. Putting the DoMagic function in a separate helper class, but the function here needs (and modifies) quite a lot of internal variables/fields. Sending them all as (reference) parameters would just look bad.
My gut tells me that the adapter pattern could have a place here, some class to convert between the two when necessary. But it also feels hacky.
I tagged this with language-agnostic since it applies to all languages that use this one-baseclass-many-interfaces approach.
Also, please point out if I seem to have misunderstood any of the patterns I named.
In C++ I would just make a class with the private fields, that function implementation and put it in the inheritance list. Whats the proper approach in C#/Java and the like?
You can use the strategy pattern or something like it to use has a (composition) instead of is a (inheritance):
public class TypeA : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class TypeB : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class Magical : IMagician {
public void DoMagic() {
// shared magic
}
}
There are other ways to instantiate your private IMagician members (such as passing them as a param via constructor) but the above should get you started.
In .Net, you can have extension methods apply to interfaces. It's really neat when it's possible, and applicable for you because it's a rare way to apply a common implementation to an interface. Certainly consider it, but it might not work for you since you say that DoMagic works with a lot of Private members. Can you package these private variables internal possibly? This way the extension method could access them.
Have the common functionality in another class. If there's a logical place to put this common functionality, pass your objects to this other class method (perhaps this is UI functionality, and you already have a UI helper . . .). Again, can you expose the private data with an internal/public property? (Security/encapsulation is a concern in all this of course. I don't know if your classes are for internal use only or will be exposed publicly.)
Otherwise, pass a separate functionality class (or specific function pointer) into the interface-defined method. You would have to have a little bit of duplicated code to pass your private variables to this external function reference, but at least it wouldn't be much, and your implementation would be in one place.
We might be making this too complicated. It won't make you feel all object-oriented when you go to sleep tonight, but could you have a static routine in your library somewhere that all IMagician implementers call?
In the end, Adapter might indeed be what you're looking for. Less likely but still worth consideration is the Decorator pattern.
If nothing seems particularly good, pick what feel best, use it a couple times, and rearrange tomorrow. :)
Replace inheritance with composition.
Move your 'common' function to separate class, create an instance of that class, and insert it to TypeA object and to TypeB object.
Your gut is correct in this case. The Adapter pattern is what you're looking for.
DoFactory has good .NET examples (that should be pretty close to their Java counterparts as well):
Adapter Design Pattern in C# and VB.NET
The composite pattern is meant for complex objects, that means the focus is on one object being made up of other objects. The strategy-pattern can be regarded as a special case of that, but a strategy does not have to be an object. I think this would apply more to your case. Then again, this heavily depends on the nature of what DoMagic() does.
public interface IMagician{ /* declare here all the getter/setter methods that you need; they will be implemented both in TypeA and TypeB, right? */ }
public static class MyExtensions {
public static void doMagic(this IMagician obj)
{
// do your magic here
}
}
Now, the problem is if you REALLY need to use private properties/methods (as opposed to "internal" ones), this approach won't work. Well, actually, you may be able to do your magic if you can read those properties through reflection, but even if it works, it's a rather ugly solution :)
[Note that "doMagic" will automatically appear to become a part of TypeA and TypeB,simply because you implement IMagician - there is no need to have any implementation there ]
You can use composition to have magician as a property of typeA and typeB
class Magician : IMagician
{
public void DoMagic()
{}
}
Class TypeA : CustomButtonUserControl
{
//property
Magician magicianInTypeA
}
Class TypeB : CustomTextUserControl
{
//property
Magician magicianInTypeB
}
abstract class Magical: CustomButtonUserControl
{
public void DoMagic()
{
// ...
}
}
public class TypeA : Magical
{
}
public class TypeB : Magical
{
}

Interface member name conflicts in ActionScript 3

I am trying to create an ActionScript 3 class that implements two interfaces. The interfaces contain member functions with different signatures but the same name:
public interface IFoo
{
function doStuff(input:int):void;
}
public interface IBar
{
function doStuff(input1:String, input2:Number):void;
}
public class FooBar implements IFoo, IBar
{
// ???
}
In C# (for example) this is not a problem because methods can be overloaded, but ActionScript does not support overloading. Is there any way to create a class that implements both interfaces?
No, unfortunately this is not possible and it's because of the reason you already pointed out: ActionScript 3 does not support member overloading. It's a shame, but it's the unfortunate truth.
It is possible to have multiple members with the same name and even the same signature in a class, however, they must be qualified by namespace in that case. For instance, this should work:
public namespace foo;
public namespace bar;
foo function doStuf(input:int):void
{
// ...
}
bar function doStuff(input1:String, input2:String):void
{
// ...
}
You then reference the methods by qualifying them like so:
foo::doStuff(1);
bar::doStuff("foo", "bar");
Unfortunately, this won't help with your problem because even though the namespaces may be in the public namespace, they are still not the same as the public namespace itself meaning you're not satisfying the contract set forth by the interfaces (everything must be public). Making a long story short; unless you use some sort of composite pattern, you're out of luck until Adobe decides to implement member overloading.
public class FooBar would have to implement both interaces and thus implment those functions listed. Problem is ActionScript does not support method overloading. It is a nice feature that I miss from C# :(