Dynamic menu creation IoC

六月ゝ 毕业季﹏ 提交于 2019-12-02 11:10:01

The first things you have to do is to make your core application extensible. Let's see a simple example.

You will have to allow your external assembly to create item entry in your main app. To do this you can create a IMenuBuilder interface in your main app.

public interface IMenuBuilder
{
    void BuildMenu(IMenuContainer container); 
}

This interface will allow external assembly to use a IMenuContainer to create MenuEntry. This interface can be defined like this :

public interface IMenuContainer 
{
    MenuStrip Menu { get; }
}

In your main form, you will have to implement IMenuContainer and call all the IMenuBuilder interface to allow them to create menu entry.

public partial class MainForm : Form, IMenuContainer
{
    public MenuStrip Menu 
    {
        get 
        {
           return this.mnsMainApp; 
        }
    }

    private void MainForm_Load(Object sender, EventArgs e)
    {
        ILifetimeScope scope = ... // get the Autofac scope
        foreach(IMenuBuilder menuBuilder in scope.Resolve<IEnumerable<IMenuBuilder>())
        {
            menuBuilder.BuildMenu(this); 
        }
    }
}

In each external assembly, you will have to implement as much IMenuBuilder as needed and one Autofac Module. In this module you will register those IMenuBuilder.

public class XXXModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<XXXMenuBuilder>()
               .As<IMenuBuilder>();
    }
}

Finally, in your core app, you will have to register all your modules provided by external assembly :

ContainerBuilder builder = new ContainerBuilder();
String path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

IEnumerable<Assembly> assemblies = Directory.GetFiles(path, "*.dll")
                                            .Select(Assembly.LoadFrom);

builder.RegisterAssemblyModules(assemblies);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!