在多个项目中使用 SqlDependency 和 SignalR 时无法找到程序集 System.Diagnostics.DiagnosticSource

问题描述 投票:0回答:2

我在一个解决方案中有两个 ASP.NET MVC 项目。管理面板和网络。我需要使用 signalR 以及每当更新通知表时显示通知。 为此,我将 SqlDependency 与 signalR 结合使用。 Web 项目运行正常,但管理项目给了我这个错误

无法找到程序集“System.Diagnostics.DiagnosticSource,Version=4.0.2.1,Culture=neutral,PublicKeyToken=cc7b13ffcd2ddd51”。

堆栈跟踪

[SerializationException: Unable to find assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.2.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.]
   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +153
   System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336
   System._AppDomain.CreateInstance(String assemblyName, String typeName) +0
   System.Data.SqlClient.SqlDependency.CreateProcessDispatcher(_AppDomain masterDomain) +62
   System.Data.SqlClient.SqlDependency.ObtainProcessDispatcher() +54
   System.Data.SqlClient.SqlDependency.Start(String connectionString, String queue, Boolean useDefaults) +1095
   System.Data.SqlClient.SqlDependency.Start(String connectionString) +13
   HelperForYourHome.Admins.Hubs.Startup.Configuration(IAppBuilder app) in C:\Users\user\Documents\Projects\HelperForYourHome\HelperForYourHome.Admin\Hubs\Startup.cs:26

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +150
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
   Owin.Loader.<>c__DisplayClass12.<MakeDelegate>b__b(IAppBuilder builder) +66
   Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +123
   Microsoft.Owin.Host.SystemWeb.<>c__DisplayClass2.<InitializeBlueprint>b__0(IAppBuilder builder) +71
   Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +462
   Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +536
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10042604
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

这是实施

欧文初创公司

[assembly: OwinStartup("Startup", typeof(Startup))]
namespace Admins.Hubs
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var idProvider = new CustomUserIdProvider();
            GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
            app.MapSignalR();
            SqlDependency.Start(Connection.ConnectionString);

            var properties = new AppProperties(app.Properties);
            CancellationToken token = properties.OnAppDisposing;
            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    SqlDependency.Stop(Connection.ConnectionString);
                });
            }
        }
    }
}

这一个启动文件正在被两个项目使用

这是我的消息处理程序类

public class MessagesRepository
{
    readonly string _connString = Connection.ConnectionString;
    public IEnumerable<NotificationMessage> GetAllMessages()
    {
        var messages = new List<NotificationMessage>();
        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (var command = new SqlCommand(@"SELECT [ID],[Title],[Description],[MessageType],[NotificationType],[Icon],[IsAjaxMessage],[IsViewMessage],[IsRedirectMessage] FROM [General].[NotificationMessage]", connection))
            {
                command.Notification = null;
                var dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                if (connection.State == ConnectionState.Closed)
                    connection.Open();
                var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    messages.Add(new NotificationMessage(reader));
                }
            }
        }
        return messages;
    }



    public virtual void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<Notification>();
            context.Clients.All.GetNotifications();
        }
    }
}

这一切都运行良好。但这仅在 Web 项目中运行良好,而在管理项目中则不起作用。

asp.net model-view-controller signalr sqldependency
2个回答
2
投票

我也有同样的问题。解决方案是在我的所有项目中升级System.Net.Http

这是 nuget 命令:

Update-Package System.Net.Http -Version 4.3.3
这是 nuget 网页:System.Net.Http nuget 页面

希望它也能帮助解决您的问题。

亲切的问候


0
投票

绑定重定向可能丢失或不正确。

不同的依赖项(例如 NuGet 包)可能会尝试加载不同版本的库,从而导致失败。然后,绑定重定向通过选择要加载的单个版本(通常是最新版本)来解决此问题。如果设置不正确,可能会出现上述错误。

完全归功于 Nick Craver 和他出色的博客文章: https://nickcraver.com/blog/2020/02/11/binding-redirects/

我将在此处包含博客文章的一部分:

  1. 启用
    <AutoGenerateBindingRedirects>
    (这不适用于 Web 项目 - 它不处理 web.config)

注意:这并不总是完美的。它不处理所有传递性 尤其是围绕多目标和条件引用的案例。

  1. 使用 Visual Studio 构建并希望它有警告并单击修复(这通常有效)

注意:这也不总是完美的,因此才有“希望”。

  1. 手动编辑您的 *.config 文件。

这是最可靠的方法(以及 Visual Studio 上面所做的),但是 也是最手动和/或最有趣的升级。

就我而言,选项 2 效果很好 - 快速且无痛。谢谢,马克!

接受的答案中建议的解决方案可能非常有效,因为直接添加 NuGet 包引用通常会设置绑定重定向,但如果您的项目并不真正使用它,则无需添加直接引用。

我知道这个问题很老了,但我最近在处理旧项目时遇到了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.