如何在一个.NET解决方案中跨项目进行沟通? [英] How to communicate across projects inside one .NET solution?

查看:101
本文介绍了如何在一个.NET解决方案中跨项目进行沟通?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET核心(UWP解决方案)应用程序,它有3个不同的项目(我们称之为A,B和C)。



A和B是Windows运行时组件和C是一个简单的类库。



项目A和B具有对项目C的引用。



我想访问一个项目C的类,其实例将在项目A和B之间共享。



我想到了一个单例模式课程),使用.NET 4的Lazy方法



问题是每次A和B项目访问实例时,实例不一样。 Lazy方法创建类的新实例,因为它似乎不是以前创建的。我想知道我是否可以在解决方案的不同项目之间分享单身人士。我已经看到一个项目与进程相关联,每个进程都有自己的内存空间,不能共享。有没有解决我的问题?



编辑
这是我的HubService类的实现:

  private static readonly Lazy< HubService> Lazy = 
new Lazy< HubService>(()=> new HubService(),LazyThreadSafetyMode.ExecutionAndPublication);

private HubService()
{
_asyncQueue = new AsyncQueue< Guid>();
}

public static HubService Instance => Lazy.Value;

另外,是否可以使用像Castle Windsor,Ninject,Autofac这样的工具在不同的程序集之间共享一个单例或Unity?

解决方案

Singleton类不会在这里工作 - 每个进程都有自己的记忆,所以它自己的单身。



在UWP中的AFAIK 用于进程间(在后台任务和主UI之间,除了音频任务)通信之外,您将需要某种经纪人。为了简化同步,您可能会想到使用 LocalSettings ,对于更复杂的场景,也可能是LocalFolder 中的文件/数据库。如果您决定使用文件,则需要同步进程,为此您可以拥有

I have a .NET Core (UWP solution) application which has 3 different projects (let's call them A, B and C).

A and B are Windows Runtime Components, and C is a simple Class Library.

Projects A and B have a reference to the project C.

I would like to access a class of the project C, whose the instance would be shared between projects A and B.

I thought to a singleton pattern (of course), using the Lazy method of .NET 4

Problem is that the instance is not the same each time A and B projects access the instance. The Lazy method creates a new instance of the class because it seems not to be previously created. I wonder if I can share a singleton between different projects of a solution. I've read that a project is associated to a process, and each process has its own memory space which cannot be shared. Is there a solution to my issue?

EDIT: Here's my implementation of my HubService class:

    private static readonly Lazy<HubService> Lazy =
        new Lazy<HubService>(() => new HubService(), LazyThreadSafetyMode.ExecutionAndPublication);

    private HubService()
    {
        _asyncQueue = new AsyncQueue<Guid>();
    }

    public static HubService Instance => Lazy.Value;

Also, is it possible to share a singleton across different assemblies using tools like Castle Windsor, Ninject, Autofac or Unity?

解决方案

Singleton class won't work here - every process will has its own memory and so its own singleton.

AFAIK in UWP for inter process (between background tasks and main UI, apart from audio task) communication you will need some kind of a broker. For short synchronization you may think of using LocalSettings, for more complicated scenarios maybe a file/database in LocalFolder. If you decide to use a file you will need to synchronize processes, for this purpose you have objects like Mutex nad WaitHandles.

这篇关于如何在一个.NET解决方案中跨项目进行沟通?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆