UserControl in Dll
March 20th, 2007Great feature of ASP.NET is that we are able to write a server control, pack it into assembly and use in many applications. However, it is quite hard to create one. On the other hand, user controls (ascx) are very easy to write but they're not so good to reuse because we must share our code.
What I am going to do today, is packing ascx file into assembly.
We need two tools:
- ASP.NET compiler (which is available in .Net Framework 2.0)
- ILMerge
All we must do is creating a simple WebApplication and delete all aspx files from it. We don't need them.
Add simple UserControl:
-
<%@ Control Language="C#" AutoEventWireup="true" ClassName="FooControl" CodeFile="FooControl.ascx.cs" Inherits="MyNamespace.FooControl" %>
-
<p>Yo!</p>
and codebehind:
-
namespace MyNamespace
-
{
-
public partial class FooControl : System.Web.UI.UserControl
-
{
-
protected void Page_Load(object sender, EventArgs e)
-
{
-
// any additional code here
-
}
-
}
-
}
Now the most interesting part. Compilation ![]()
We need to compile the whole project as if it was regular ASP.NET page:
aspnet_compiler.exe -p c:\\path_to_page_source -fixednames c:\\temp\\precompiled_page
Then we will have precompiled web page right in c:\temp\precompiled_page folder.
We are interested only in Bin folder - there is a file looking like App_Web_foocontrol.ascx.cdcab7d2.dll - it can look a little bit different because cdcab7d2 is a hash code that represents the directory that the original file was in. This is used to avoid naming conflicts in case you have files with the same name in different directories (common situation for default.aspx)
We can do two things right now:
- use assembly with this crappy name
- use ILMerge to convert it to more friendly name
ILMerge is designed to pack several assemblies into one but we will use it just for creating another name (we can't just rename the file, it won't work)
ilmerge.exe /ndebug /out:our.brand.new.dll c:\\temp\\precompiled_page\\bin\\App_Web_foocontrol.ascx.cdcab7d2.dll
Voila, we've got a new dll with cool name and what's important: there is an ascx file in it ![]()
Only embed it on a web page:
-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
<%@ Register TagPrefix="wc" namespace="ASP" Assembly="our.brand.new" %>
-
<html>
-
<body>
-
<form id="MyForm" runat="server">
-
<div>
-
<wc:FooControl runat="server" ID="Foo" />
-
</div>
-
</form>
-
</body>
-
</html>
Very important is the namespace which is ASP. We cannot use our namespace because that class is just a base class and it will not render child controls. We must call inherited class which is in ASP namespace. Use Reflector to see what I am talking about.

Great, exactly what I was looking for, I need my plugins to be single assemblies for my CMS, this solved my problem, thanks, I’ll probably make some winform application, because this is a horror