In response to my question here that was half way about having a circular dependency:
C# ASP.NET Dependency Injection with IoC Container Complications
The presenter depends on an IView. And the Page (implementing the IView) depends on a presenter. Other have solved this converting from constructor injection to property injection
I didnt like this because I felt that you now need to make public properties that can be modified externally, and also becomes the developers responsibilityies to initialise.
But it seems that I have been able to solve this another way.
By the page having a default constructor as well as an overloaded parameterised constructor, you can via reflection call the parameterless constructor to create the object then call the overloaded one by injecting the dependencies.
I'ill illustrate by example:
class TestObject
{
public string Name { get; set; }
public TestObject()
{
Name = "Constructed with no args";
Console.WriteLine("constructor hash code: " + GetHashCode());
}
public TestObject(string name)
{
this.Name = name;
Console.WriteLine("constructor hash code: " + GetHashCode());
}
}
This object can be constructed simply:
var obj = Activator.CreateInstance<TestObject>();
or
var obj = new TestObject();
But then I can via reflection use the overloaded constructor to inject the dependencies:
ConstructorInfo ctor = obj.GetType().GetConstructors()[1];
ctor.Invoke(obj, new[] { "injected" });
I was able to use this approach to wire up structuremap to register the instance after creation and then inject the dependencies.
Of course we can use a regular method to inject the dependencies, but this again breaks the encapsulation a bit, so you could call this again to override dependencies.
Also as constructor this cant simply be reached by static code.
But I have no idea how I feel about this, it feels a little bit like a hack or something that i can simply do accidentally in C#.
I would like to hear your thoughts
Thanks.