N.B., this is all C# 4.0
This might seem like an odd question, let us say that all my business objects bind to a base class, let’s call it BaseObject, so I’ll have my classes inherit it like so:
public class CashRegister : BaseObject { }
Now most of the time I’m using, say, NHibernate on my projects. Some other projects come along and I’d like to use CouchDb. Rather than create a new BaseObject for each of these technologies, I’d like to somehow “bind” something like CouchDbObject to BaseObject … is this possible? Even better would be if I had an attribute and it would bind based on the attribute:
[CouchDb]
public class CashRegister : BaseObject { }
This might be crazy, but is it possible? Given the above example, I’d liek to do this:
var cashRegister = new CashRegister();
cashRegister.SomeGenericBaseObjectMethod();
cashRegister.SomeCouchDbSpecificMethod();
It seems that Ninject “contextual binding” does what I need, does it? I’m brainstorming right now, but it would be great if somewhere in my code I could do something like this to do the actual binding:
Bind<ICouchDbObject>.To<BaseObject>();
I would even be up for making BaseObject dynamic, or any other bleeding edge features that might make this possible. If this is not possible or a “don’t,” let me know! Trying to think outside the box.
No, what you’re asking isn’t possible, for a couple of reasons.
Usually when you run into a situation where you want to do what you’re describing, it’s because you’re using an architecture that doesn’t separate concerns well enough. I’m just guessing here, but you’ll probably be more flexible if you use an approach like this:
You’ll notice that so far we don’t have any code that relies on CouchDb. Now, say there’s another project that wants to be able to use the above project, but wants to be able to perform additional operations based on the CouchDb information. You might do something like this:
In this project, when you need a cash register, you would use a
CouchDbCashRegister, which would allow you to call the CouchDb-specific methods on yourCouchDbUtilclass, while still allowing you to call the baseline utility methods in yourBaseObjectUtilclass.Furthermore, if you leverage a DI framework like Ninject to create your objects, you can actually make it so that all CashRegisters that get created in your second project are actually CouchDbCashRegisters.