通过 Ioc 和默认实例提供 class 的最佳实践
Best practice for having a class served via Ioc and Default instance
在 WPF 中,我有一个名为 UserMessageService 的 class,我用它来发送用户消息。我已经将它实现为单例,但我也想通过 IoC 公开它
public class UserMessageService : IUserMessageService
{
private static UserMessageService userMessageService;
private static readonly object objLock = new object();
private readonly IMessageMediator messageMediator;
private UserMessageService()
{
messageMediator = ServiceLocator.Default.ResolveType<IMessageMediator>();
}
public static UserMessageService Default
{
get
{
lock (objLock)
{
return userMessageService ?? (userMessageService = new UserMessageService());
}
}
}
public void SendMessage(string message,LogMessageTypeEnum type =LogMessageTypeEnum.Info)
{
var userMessage = new UserMessage
{
Message = message,
LogMessageType = type
};
messageMediator.SendMessageAsync(userMessage);
}
}
这样做的最佳做法是什么?
更新#1
我在注册代码中添加了这个(对于其他 Catel 用户)
serviceLocator.RegisterType<IUserMessageService>((x) => UserMessageService.Default);
创建一个工厂方法并配置 IoC 容器以将此工厂方法用于类型 UserMessageService
例子
IoCContainer.For<UserMessageService>().Use(() => return UserMessageService.Default);
在 WPF 中,我有一个名为 UserMessageService 的 class,我用它来发送用户消息。我已经将它实现为单例,但我也想通过 IoC 公开它
public class UserMessageService : IUserMessageService
{
private static UserMessageService userMessageService;
private static readonly object objLock = new object();
private readonly IMessageMediator messageMediator;
private UserMessageService()
{
messageMediator = ServiceLocator.Default.ResolveType<IMessageMediator>();
}
public static UserMessageService Default
{
get
{
lock (objLock)
{
return userMessageService ?? (userMessageService = new UserMessageService());
}
}
}
public void SendMessage(string message,LogMessageTypeEnum type =LogMessageTypeEnum.Info)
{
var userMessage = new UserMessage
{
Message = message,
LogMessageType = type
};
messageMediator.SendMessageAsync(userMessage);
}
}
这样做的最佳做法是什么?
更新#1
我在注册代码中添加了这个(对于其他 Catel 用户)
serviceLocator.RegisterType<IUserMessageService>((x) => UserMessageService.Default);
创建一个工厂方法并配置 IoC 容器以将此工厂方法用于类型 UserMessageService
例子
IoCContainer.For<UserMessageService>().Use(() => return UserMessageService.Default);