Compile web application project ascx into dll

前端 未结 6 1474
孤独总比滥情好
孤独总比滥情好 2021-01-02 04:36

Is it possible to compile a web application project .ascx (user control) into a dll?

I want to do the following:

  1. Use the same control in multiple websi
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 05:23

    Conversion is easy, and could even be fully automated. It simply requires changing a few settings and base classes in the DLL Project you want your ASCX controls embedded in.

    1... For each UserControl, set the ASCX file's Build Action (under Properties) to "Embedded Resource", and delete its associated designer file.

    2... Save the project.

    3... Right click the project and choose "Unload Project".

    4... Right click it again and choose the "Edit *.csproj" option.

    Change sections that look like this (where the asterisk represents your class name):

    
        *.ascx
        ASPXCodeBehind
    
    

    to look like this

    
    

    That will cause the code-behind files to be compiled independently of the ASCX files.

    5... Save changes, and right click the project and choose "Reload Project".

    6... Open all your "*.ascx.cs" files and make them inherit from the following custom UserControl class, instead of the System.Web.UI.UserControl class (you may need to locate parent classes to complete this step).

    public class UserControl : System.Web.UI.UserControl
    {
        protected override void FrameworkInitialize()
        {
            base.FrameworkInitialize();
            string content = String.Empty;
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( GetType().FullName + ".ascx" );
            using (StreamReader reader = new StreamReader(stream))
                content = reader.ReadToEnd();
            Control userControl = Page.ParseControl( content );
            this.Controls.Add( userControl );
        }
    }
    

    This base class will take care of loading and parsing the embedded ASCX file.

    7... Finally, you may need to place ASCX files in subfolders so that their resource names (automatically determined by folder path) match the full type name of their associated class (plus ".ascx"). Assuming your root namespace matches your project name, then a class named "ProjectName.Namespace1.Namespace2.ClassName" will need its ASCX file in a subfolder "Namespace1\Namespace2", so it gets embedded with the name "ProjectName.Namespace1.Namespace2.ClassName.ascx".

    And that's it! Once you compile the DLL and include it in another project, you can instantiate instances of your user controls using the "new" operator, like any other class. As always, your control will be "caught up" to the current page event once added as a child control to the page or another control on the page.

提交回复
热议问题