Skip to content

Instantly share code, notes, and snippets.

@adrianiftode
Last active October 25, 2016 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrianiftode/bec4c3c4a9e1e18160b122cade7382a2 to your computer and use it in GitHub Desktop.
Save adrianiftode/bec4c3c4a9e1e18160b122cade7382a2 to your computer and use it in GitHub Desktop.
///This example demonstrates why DI doesn't properly work with ASP .Net WebForms
///Based on https://blogs.msdn.microsoft.com/webdev/2016/10/19/modern-asp-net-web-forms-development-dependency-injection/
void Main()
{
// ASP .Net creates a GeneratedPage
var page = new GeneratedPage();
//Glue code to inspect this object
var pageType = page.GetType().BaseType;
// Determine if there is a constructor to inject, and grab it
var ctor = (from c in pageType.GetConstructors()
where c.GetParameters().Length > 0
select c).FirstOrDefault();
//Invoke ctor and injected dependencies
ctor.Invoke(page, new [] { new Repository() });
//what's my output now?
page.GetMyState()
//.Dump()
;
//This is it
/*
I'm created by the framework in the BasePage
I'm created by the framework in the Edit Page.
I'm created by the framework, now I am the GeneratedPage type.
I'm I building this part again? I'm I called via a reflection API?
I'm created by the framework in the BasePage
Oh my, I'm injected with this UserQuery+Repository from a IoC container!
*/
}
public class Repository
{
public Repository()
{
}
}
//most applications have a BasePage, there are even libraries that provide a BasePage to hook for the page life cycle
public class BasePage
{
protected string state;
//This will be called a second time with ctor.Invoke.
//First time was called by the ASP .Net WebForms framework when GeneratedPage has been initialized.
//This is another reason why MVC and other frameworks provide access points to delegate the GeneratedPage
//creation to an IoC Container and not to work with an already created instance.
protected BasePage()
{
if (state != null && state.Contains("BasePage"))
{
state += "\n I'm I building this part again? I'm I called via a reflection API?";
}
state += "\nI'm created by the framework in the BasePage";
}
}
public class EditPage : BasePage
{
public EditPage(Repository repository)
{
state += $"\nOh my, I'm injected with this {repository} from a IoC container!";
}
protected EditPage()
{
state += "\nI'm created by the framework in the Edit Page.";
}
public string GetMyState()
{
return state;
}
}
public class GeneratedPage : EditPage
{
public GeneratedPage()
{
state += "\nI'm created by the framework, now I am the GeneratedPage type.";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment