【问题标题】:Adding connection to LINQPad gives Unity.ResolutionFailedException添加到 LINQPad 的连接会产生 Unity.ResolutionFailedException
【发布时间】:2016-07-21 17:28:56
【问题描述】:

我正在尝试在 LINQPad 中创建一个简单的 C# 程序来测试一些 DbContext 的东西。我设置了与我的 DataModels 程序集和配置文件的连接。但是,当我尝试运行该程序时,我会收到以下消息:

ResolutionFailedException:依赖项解析失败,type = "Clark.Logging.ILogger",name = "(none)"。 异常发生时:解决时。

异常是:InvalidOperationException - 当前类型 Clark.Logging.ILogger 是一个接口,无法构造。您是否缺少类型映射?

发生异常时,容器为:

正在解决 Clark.Logging.ILogger,(无)

到目前为止,程序很简单:

void Main()
{
    var testString = "Testing";
    testString.Dump();

    // More code to eventually go here, which will use the connection and context.
}

如果我不选择我的连接,这将有效。

我相信 DataModel 程序集使用 Unity IoC 进行自定义日志记录设置。出于某种原因,只是将此 LINQPad 文件与连接相关联会导致错误。

我可能需要在此处提供更多信息,但我该怎么做才能使用我的连接?

【问题讨论】:

  • 看起来您用于 EF 连接属性的 DataContext 库依赖于您未引用的另一个库,或者当它在您的主项目中使用时,还有其他绑定不是满足(至少一个)其依赖项所需的 DataContext 库的一部分。

标签: c# ioc-container dbcontext linqpad


【解决方案1】:

Unity 找不到映射,它会尝试构造类型。在您的情况下,它失败了,因为您无法构造接口。

使用 Unity,您可以通过以下方式进行配置:

container.RegisterType<InterfaceType, ConcreteType>();

更新#

请在下方尝试,看看是否有帮助。

void Main()
{
  ILogger log = new Logger();   
  var source = new Subject<int>();
  source.Log(log, "Sample")
      .Subscribe();

  source.OnNext(1);
  source.OnCompleted();
}

广播任何已配置的侦听器/附加器实例的日志条目以在适当时写入

  1. 日志级别
  2. 要记录的消息
  3. 与日志关联的可选异常实例。用于捕获堆栈跟踪。

    公共接口 ILogger { void Write(LogLevel 级别,字符串消息,Exception 异常); } 公共类记录器:ILogger { public void Write(LogLevel 级别,字符串消息,Exception 异常) { message.Dump(level.ToString()); } }

    公共枚举 LogLevel { /// /// 最低级别,用于任何被认为是详细的信息。 /// 冗长, /// /// 第二低级别,用于在详细日志记录中跟踪工作流。 /// 痕迹, /// /// 用于记录可能有助于调试问题的信息。 /// 调试, /// /// 发生了一个非严重错误,不会中断应用程序,但可能会降低用户体验。 /// 警告, /// /// 用于有趣的业务或技术操作,例如启动流程或发出请求。 /// 信息, /// /// 对于需要立即注意的错误。 /// 错误, /// /// 对于灾难性故障。 /// 致命的 }

接口的扩展方法。

public static class LoggerExtensions
{
    /// <summary>
    /// Logs a message with an exception as Fatal.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Fatal(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Fatal, formattedMessage, exception);
    }
    /// <summary>
    /// Logs a message with an exception as Fatal.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Fatal(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Fatal(null, format, args);
    }

    /// <summary>
    /// Logs a message with an exception as Error.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Error(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Error, formattedMessage, exception);
    }
    /// <summary>
    /// Logs a message with an exception as Error.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Error(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Error(null, format, args);
    }

    /// <summary>
    /// Logs a message with an exception as Info.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Info(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Info, formattedMessage, exception);
    }
    /// <summary>
    /// Logs a message with an exception as Info.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Info(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Info(null, format, args);
    }

    /// <summary>
    /// Logs a message with an exception as Warn.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Warn(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Warn, formattedMessage, exception);
    }
    /// <summary>
    /// Logs a message with an exception as Warn.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Warn(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Warn(null, format, args);
    }

    /// <summary>
    /// Logs a message with an exception as Debug.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Debug(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Debug, formattedMessage, exception);
    }
    /// <summary>
    /// Logs a message as Debug.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Debug(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Debug(null, format, args);
    }

    /// <summary>
    /// Logs a message with an exception as Trace, the second lowest level.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Trace(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Trace, formattedMessage, exception);
    }
    /// <summary>
    /// Logs a message as Trace, the second lowest level.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Trace(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Trace(null, format, args);
    }

    /// <summary>
    /// Logs a message with an exception as Verbose, the lowest level.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Verbose(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Verbose, formattedMessage, exception);
    }
    /// <summary>
    /// Logs a message as Verbose, the lowest level.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Verbose(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Verbose(null, format, args);
    }

    private static string Format(string format, params object[] args)
    {
        if (args == null || args.Length == 0)
            return format;
        return string.Format(CultureInfo.CurrentCulture, format, args);
    }

    /// <summary>
    /// Logs the entry to a method as a string like "MyType.MyMethod(1, ABC)". 
    /// Ensure the method being logged is not in-lined by the compiler/jitter with the
    /// [MethodImpl(MethodImplOptions.NoInlining)] attribute.
    /// </summary>
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="args">The arguments passed to the method</param>
    /// <remarks>
    /// The <see cref="MethodEntry"/> logging method is useful for logging that a method has 
    /// been entered and also capturing the arguments of the method in the log.
    /// <example>
    /// In this example we log a method entry and the arguments.
    /// <code>
    /// <![CDATA[
    /// [MethodImpl(MethodImplOptions.NoInlining)]
    /// public void MyLoggedMethod(string s, DateTime dateTime)
    /// {
    ///     _logger.MethodEntry(s, dateTime);
    ///     //Method body goes here...
    /// }
    /// 
    /// ]]>
    /// </code>
    /// The output may look something like this
    /// 2012-01-31 12:00 [UI] DEBUG MyLoggedType.MyLoggedMethod(A, 31/12/2001 13:45:27)
    /// </example>
    /// </remarks>
    public static void MethodEntry(this ILogger logger, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var stackTrace = new StackTrace();
        var method = stackTrace.GetFrame(1).GetMethod();
        var type = method.DeclaringType;
        var typeName = string.Empty;
        if (type != null) typeName = type.Name;
        string parenth = "()";
        var parameterDefinitions = method.GetParameters();
        if (parameterDefinitions.Length > 0)
        {
            if (args == null || args.Length == 0)
            {
                parenth = "(...)";
            }
            else
            {
                var values = string.Join(", ", args);
                parenth = string.Format(CultureInfo.CurrentCulture, "({0})", values);
            }
        }

        logger.Debug("{0}.{1}{2}", typeName, method.Name, parenth);
    }

    public static IObservable<T> Log<T>(this IObservable<T> source, ILogger logger, string name)
    {
        return Observable.Using(
            () => logger.Time(name),
            timer => Observable.Create<T>(
                o =>
                {
                    logger.Trace("{0}.Subscribe()", name);
                    var subscription = source
                        .Do(
                            i => logger.Trace("{0}.OnNext({1})", name, i),
                            ex => logger.Trace("{0}.OnError({1})", name, ex),
                            () => logger.Trace("{0}.OnCompleted()", name))
                        .Subscribe(o);
                    var disposal = Disposable.Create(() => logger.Trace("{0}.Dispose()", name));
                    return new CompositeDisposable(subscription, disposal);
                })
            );
    }

    public static IDisposable Time(this ILogger logger, string name)
    {
        return new Timer(logger, name);
    }

    private sealed class Timer : IDisposable
    {
        private readonly ILogger _logger;
        private readonly string _name;
        private readonly Stopwatch _stopwatch;

        public Timer(ILogger logger, string name)
        {
            _logger = logger;
            _name = name;
            _stopwatch = Stopwatch.StartNew();
        }

        public void Dispose()
        {
            _stopwatch.Stop();
            _logger.Debug("{0} took {1}", _name, _stopwatch.Elapsed);
        }
    }
}

【讨论】:

  • 在我的代码中,我执行var multiLogger = new MultiLogger(); IoCHelper.RegisterInstance&lt;ILogger&gt;(multiLogger); 之类的操作。但只是将它添加到我在 LINQPad 中的Main() 并不能修复错误。
  • 使用可以在 LinqPad 中尝试的示例代码进行编辑
  • 我收到了CS0246 The type or namespace name 'Logger' could not be found (press F4 to add a using directive or assembly reference)。尝试使用 log4net 会干扰我们的自定义日志记录类。
  • 按 F4 并添加以下引用,System System.Reactive System.Reactive.Concurrency System.Reactive.Disposables System.Reactive.Joins System.Reactive.Linq System.Reactive.Subjects System.Reactive.Threading.Tasks System.Windows.Forms System.Globalization
  • 我不确定这对我有什么帮助。使用这个 DbContext 的原始代码没有使用 Reactive。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
  • 2012-11-23
  • 2020-02-22
  • 1970-01-01
相关资源
最近更新 更多