Constructor Injection from Base Type

468 views
Skip to first unread message

Neilski

unread,
Mar 9, 2011, 2:49:52 AM3/9/11
to ninject
I'm new to Ninject, so please bear with me. This is what I'd like to
achieve...

I have a base class with a single public constructor:

public class BaseClass
{
public BaseClass(string connectionString)
{
}
}


I then have a number of classes that derive from this base class:

public ClassA : BaseClass
{
public ClassA(string connectionString) : base(connectionString)
{
}
}


What I would like to be able to achieve is to 'inject' the
connectionString value into all class instances derived from
BaseClass. Something like this:


Bind<RoomarBaseRepository>().WithConstructorArgument("connectionString",
MyConnectionString);


Is this possible? If so, can anyone help me with the required
construction?

Thanks.

Remo Gloor

unread,
Mar 9, 2011, 8:30:21 AM3/9/11
to ninject
No, you can't define parameters for a base class.

But what you can do is to add a conditional binding for string insted.
Bind<string>().ToConstant(MyConnectionString).When ...

Here you have some options:
1.
When(request =>
typeof(BaseClass).IsAssignableTo(request.Target.ReflectedType))

2. Create a ConectionStringAttribute and use
WhenTargetHas<ConectionStringAttribute>()
public ClassA([ConectionStringAttribute]string connectionString) :
base(connectionString)

3. Use the convention the all connection strings parameters have
the same name
WhenTargetNamed<"connectionString">()

And create the following extension method
public static IBindingInNamedWithOrOnSyntax<T>
WhenTargetNamed<T>(this IBindingWhenSyntax<T> syntax,
string name)
{
return syntax.When(
request =>
request.Target != null &&

request.Target.Name.ToUpper(CultureInfo.InvariantCulture) ==
name.ToUpper(CultureInfo.InvariantCulture));

outinsun

unread,
Mar 25, 2011, 6:03:47 PM3/25/11
to ninject
I did the following in Ninject 2.0 in order to use interface injection
with a base class that enforces proper constructor setup for the
implementing classes:

public interface IFoo
{
void nothing();
}

public class FooBase : IFoo
{
protected readonly string _string;
protected FooBase(string randomString)
{
_string = randomString;
}
public abstract void nothing();
}
public class RealFoo : FooBase
{
public RealFoo(string randomString) : base(randomString)
{
}
void override nothing()
{
Console.WriteLine(_string);
}
}


Now for the Ninject part:

Bind<IFoo>().To<RealFoo>(); // just like normal

string localString = "blah";
_kernel.Get<IFoo>( new ConstructorArgument("randomString",
localString) );
Reply all
Reply to author
Forward
0 new messages