我试图将TextLogger
注入到应用程序中,但是我在努力将实际文件路径注入到构造函数中。
下面是我的ILogWriter
和TextLogger
班
ILogWriter:
public interface ILogWriter
{
void WriteLog (string message);
}
TextLogger:
public class TextLogger : ILogWriter
{
[InjectionConstructor]
public TextLogger (string filePath)
{
this.FilePath = filePath;
this.WriteLog ("test");
}
public string FilePath { get; set; }
public void WriteLog (string message)
{
using ( var writer = File.AppendText(this.FilePath))
{
writer.WriteLine(message);
}
}
}
我尚未将其注入任何东西,因为我的代码在构造过程中中断了:
public partial class App : Application
{
/// <summary>
/// Startup Logic for App
/// </summary>
/// <param name="e"></param>
protected override void OnStartup (StartupEventArgs e)
{
base.OnStartup(e);
// Dependency Injection
IUnityContainer container = new UnityContainer();
// Logging
var filePath = "C:/mypath/testing.txt";
container.RegisterType<ILogWriter, TextLogger>(new InjectionConstructor(filePath));
// It will be injected into my LoggingService, but breaks just before when writing the test message
container.RegisterType<ILoggingService, LoggingService>();
// Notifications
container.RegisterType<INotificationService, NotificationService>();
// Data Contexts
container.RegisterType<IViewModelLocator, ViewModelLocator>();
container.RegisterType<MainWindow>();
container.Resolve<MainWindow>().Show();
}
}
运行时发生以下错误:
值不能为空
当我检查FilePath
变量时,它为null。如何将文件路径传递到我的TextLogger
类中?