简体   繁体   中英

Sharing application data in different assemblies

I am quite new to C# / WPF , however this is what I used for this project.

Let me introduce the context : I have an application which allows a user to login. I have some basic information data (physical location) and some dynamic information (user name...). I dealed with all of that with a singleton manager .

This basic application is used with two different projects : after login, the application has to display xaml pages for the current running project.

Some configuration enum allows me to instanciate the right object from the right project assembly through a generic interface ( I guess I should have use WCF... we'll see that later on :) ).

Now I need some of the information, dealed by the singleton manager, in the project assembly. How can I do ?

I can't share the singleton... Should i write a common db ? Or get rid of the singleton ? I am a bit lost. This is certainly simple architecture problem, but I can't figure it out.

Thanks a lot for your help !

I suggest you use MEF for importing and exporting information from different DLL's. Each DLL could have resources (like XAML files) for view providing. So, my choice is MVVM + MEF modularity + Prism EventAggregator for interaction beetwen modules. Some samples, for concept demonstration only:

Kind of 'singleton manager':

public class AddinsManager : IAddinsManager
{
    [ImportMany(typeof(IModule))]
    private OrderingCollection<IModule, IOrderMetadata> modules = new OrderingCollection<IModule, IOrderMetadata>(lazyRule => lazyRule.Metadata.Order);

    private CompositionContainer container;
    private bool isInitialized = false;

    /// <summary>
    /// Gets available application modules (add-ins)
    /// </summary>
    public List<IModule> Modules { get; private set; }

    /// <summary>
    /// Initialize manager
    /// </summary>
    public void Initialize()
    {
        Assembly oAssembly = Assembly.GetAssembly(Application.Current.GetType());
        this.container = new CompositionContainer(GetCatalog(oAssembly));
        this.container.ComposeParts(this, Context.Current);

        this.Modules = this.modules
                            .Select(lazy => lazy.Value)
                            .ToList();

        this.isInitialized = true;
    }

    /// <summary>
    /// Initialize modules
    /// </summary>
    public void InitializeModules()
    {
        foreach (IModule oModule in this.Modules)
        {
            oModule.Initialize();
        }
    }

    /// <summary>
    /// Injects dependencies in specified container
    /// </summary>
    /// <param name="host">Container to inject in</param>
    public void Compose(object host)
    {
        if (host == null)
        {
            throw new ArgumentNullException();
        }

        this.EnsureInitialize();

        this.container.ComposeParts(host);
    }

    /// <summary>
    /// Register views of the modules
    /// </summary>
    public void RegisterViews()
    {
        this.EnsureInitialize();

        foreach (IModule oModule in this.Modules)
        {
            foreach (Uri oUri in oModule.GetViewPath().ToArray())
            {
                ResourceDictionary oDictionary = new ResourceDictionary();
                oDictionary.Source = oUri;
                Application.Current.Resources.MergedDictionaries.Add(oDictionary);
            }
        }
    }

    /// <summary>
    /// Get catalog for modules load
    /// </summary>
    /// <param name="assembly">Assembly to search modules</param>
    /// <returns>Catalog for modules load</returns>
    private static AggregateCatalog GetCatalog(Assembly assembly)
    {
        string sDirName = Path.GetDirectoryName(assembly.Location);
        DirectoryCatalog oDirCatalog = new DirectoryCatalog(sDirName, "Company.*");
        AssemblyCatalog oAssemblyCatalog = new AssemblyCatalog(assembly);

        AggregateCatalog oCatalog = new AggregateCatalog(oAssemblyCatalog, oDirCatalog);
        return oCatalog;
    }

    /// <summary>
    /// Ensure if manager was initialized
    /// </summary>
    private void EnsureInitialize()
    {
        if (!this.isInitialized)
        {
            throw new Exception("Add-ins Manager Component not initialized");
        }
    }
}

Module (DLL for separate project) implementation

[Export(typeof(IModule))]
public class LayoutsModule : AModule
{
    private static LayoutsVM viewModel;

    /// <summary>
    /// Gets reporting add-in main view model
    /// </summary>
    public static LayoutsVM ViewModel
    {
        get
        {
            if (viewModel == null)
            {
                viewModel = Context
                                .Current
                                .LayoutManager
                                .ModulesVM
                                .OfType<LayoutsVM>()
                                .FirstOrDefault();
            }

            return viewModel;
        }
    }

    /// <summary>
    /// Initialize module
    /// </summary>
    public override void Initialize()
    {
        Context
            .Current
            .EventAggregator
            .GetEvent<MenuInitializing>()
            .Subscribe(this.InitializeMenu);

        base.Initialize();
    }
}

View as embeded resource (View.xaml) on each DLL.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:vm="clr-namespace:Company.Client.ViewModels">

    <DataTemplate DataType="{x:Type vm:ApplicationVM}">
        <ContentPresenter Content="{Binding AddinsViewModel}" />
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:MenuVM}">        
        <ContentPresenter Content="{Binding RibbonData}" />
    </DataTemplate>

</ResourceDictionary>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM