Using Inheritance rather than Interfaces

Feb 4, 2012 at 12:54 PM

I have a bunch of classes that are all derived from a base class rather than from an interface. What is the best way of handling this situation?

At the moment, I have created a dummy Interface which doesn't define any signatures, but the base class 'implements' this interface.

Then I register any class that Implements this interface and resolve it based on the interface and using then cast it back to the base class, something like this.

BaseClass t =  (BaseClass) container.Resolve<ITest>(name, new ResolverOverride[] { });

Is there a better way of doing this?

 


Mar 22, 2012 at 5:50 AM

I have the same problem.

 

.Include(If.Is<DbContext>, Then.Register(). UsingLifetime<PerResolveLifetimeManager>())

I have a derived class from DbContext, like MyContext, and I need to resolve it by container.Resolve<DbContext>() pointing to my MyContext class. 

 

Only works when I set implement a dummy interface in my derived dbcontext.

Mar 22, 2012 at 6:25 AM
Edited Mar 22, 2012 at 6:38 AM

I guess I've found a way to register the base class, pointing to the found subclass:

var strAssembliesToLoad = ConfigurationManager.AppSettings["assembliesToLoad"];
                if (!string.IsNullOrEmpty(strAssembliesToLoad))
                {
                    var items = strAssembliesToLoad.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    var registration = container
                        .ConfigureAutoRegistration()
                        .ExcludeSystemAssemblies();
                    foreach (var item in items)
                    {
                        registration.LoadAssemblyFrom(item.Trim());
                    }

                    registration
                        .Include(If.Implements<IUnitOfWork>, Then.Register().As<IUnitOfWork>().UsingLifetime<PerResolveLifetimeManager>())
                        .Include(t => t.IsSubclassOf(typeof(DbContext)), (tt, c) => c.RegisterType(typeof(DbContext), tt))
.ApplyAutoRegistration();

.Include(t => t.IsSubclassOf(typeof(DbContext)), (subclass, c) => c.RegisterType(typeof(DbContext), subclass, new PerResolveLifetimeManager()))

Mar 31, 2012 at 6:01 PM
Edited Mar 31, 2012 at 6:02 PM

Thanks for the reply.

I went ahead and implemented a dummy interface to my classes which works, so I don't need this now.

But I just tried your codes and I still can't get it to work in my situation where I have several classes and I need to resolve by name.

For example, if I call

var myContext = container.Resolve<DbContext>( );
then myContext will be one of my dervived class, (so I guess it will work if there is only one registered class,) but I need be able to specify the name of the class I want to use, but
var myContext = container.Resolve<DbContext>(dbContextName );
ends up with myContext being of type DbContext regardless of the name of the class passed.