I have wrapper classes for some 3rd party classes without interfaces, and I need to reference it in a fairly SOLID block of C# code.
At present, I have a static function to convert the instance into a wrapper instance.
Example Code.
class A
{
public string Name;
}
interface IAWrapper
{
string Name { get; set; }
}
class AWrapper : IAWrapper
{
private A Instance;
public AWrapper(A instance)
{
Instance = instance;
}
public string Name
{
get
{
return Instance.Name;
}
set
{
Instance.Name = value;
}
}
}
I want a function like
var a = new A() {Name = "bob"};
var wrapped = kernel.wrap<IAWrapper>(a);
Where wrapped
will be an instance of AWrapper
, and it was passed a
for Instance
Does Ninject possess a way to do this? To request a wrapper class interface, the instance to be wrapped, and get back the wrapped class?
(my apologies, I'm sure there are much more clear ways to ask this, but if I knew how to ask it better, I might know the answer as well. :) )
Assuming that the kernel was already bound you can use ConstructorArgument
to specify constructor arguments. The name of the constructor parameter is the first argument of the class.
var a = new A() { Name = "bob" };
var instance = new Ninject.Parameters.ConstructorArgument("instance", a);
var wrapper = kernel.Get<IAWrapper>(instance);
Where wrapped
will be an instance of AWrapper
, and it was passed a
for instance
parameter in the constructor.