【发布时间】:2015-02-05 11:57:40
【问题描述】:
我最近遇到了 ASP.net vnext 的AssemblyNeutral 属性。
如果我必须具体说明,那么您会在 Logging 存储库中找到该属性的用法。 https://github.com/aspnet/logging
还有许多其他存储库,但这是一个简单的存储库。
现在根据许多博客,如果我们使用AssemblyNeutral 属性,那么该接口或类型不与程序集绑定,因此我们可以在需要相同合同的其他框架中定义具有AssemblyNeutral 属性的相同接口。
所以创建示例我在 ASP.net vnext 类库项目中创建了自己的小型记录器库,但它给了我类型转换错误。
namespace MyLogger
{
#if ASPNET50 || ASPNETCORE50
[Microsoft.Framework.Runtime.AssemblyNeutral]
#endif
public interface ILogger
{
void Write(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter);
bool IsEnabled(LogLevel logLevel);
IDisposable BeginScope(object state);
}
#if ASPNET50 || ASPNETCORE50
[Microsoft.Framework.Runtime.AssemblyNeutral]
#endif
public interface ILoggerFactory
{
ILogger Create(string name);
void AddProvider(ILoggerProvider provider);
}
#if ASPNET50 || ASPNETCORE50
[Microsoft.Framework.Runtime.AssemblyNeutral]
#endif
public interface ILoggerProvider
{
ILogger Create(string name);
}
#if ASPNET50 || ASPNETCORE50
[Microsoft.Framework.Runtime.AssemblyNeutral]
#endif
public enum LogLevel
{
Verbose = 1,
Information = 2,
Warning = 3,
Error = 4,
Critical = 5,
}
public class MyLogger : ILogger
{
public IDisposable BeginScope(object state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Write(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
{
System.IO.File.AppendAllText("C:\\Testlog.txt", "This is test log" + System.Environment.NewLine);
}
}
public class MyLoggerProvider : ILoggerProvider
{
private readonly Func<string, LogLevel, bool> _filter;
public MyLoggerProvider(Func<string, LogLevel, bool> filter)
{
_filter = filter;
}
public ILogger Create(string name)
{
return new MyLogger();
}
}
public static class MyLoggerExtentions
{
public static ILoggerFactory AddMyLogger(this ILoggerFactory factory, Func<string, LogLevel, bool> filter)
{
factory.AddProvider(new MyLoggerProvider(filter));
return factory;
}
}
}
现在我正在尝试在 SampleApp(Logging Repository SampleApp)中使用。你可以看到它给了我 Cast Error。为什么这样 ?
【问题讨论】:
标签: asp.net-core