将连接添加到LINQPad会出现Unity.ResolutionFailedException

本文关键字:Unity ResolutionFailedException LINQPad 连接 添加 | 更新日期: 2023-09-27 17:58:10

我正试图在LINQPad中创建一个简单的C#程序来测试一些DbContext内容。我设置了到DataModels程序集和配置文件的连接。然而,当尝试运行程序时,我收到了以下消息:

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

异常为:InvalidOperationException-当前类型Clark.Loggin.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文件与连接关联会导致错误。

我可能需要在此处提供更多信息,但如何使用我的连接?

将连接添加到LINQPad会出现Unity.ResolutionFailedException

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级别,字符串消息,异常异常);}公共类Logger:ILogger{public void Write(LogLevel级别,字符串消息,异常异常){消息转储(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);
        }
    }
}