我在当前的Windows Phone项目中使用SterlingDB,我希望能够使用MVVM Light v4中的新SimpleIoC容器从我的应用程序中的各个位置解析Sterling数据库。
但是,我不确定SimpleIoC是否支持注册单例。 SterlingDB引擎只应在应用程序首次启动时创建,并且我不希望每次容器为其注入引用时都会启动新实例。
如果有不同的方式我应该考虑这个问题,我也很乐意接受替代方案。
答案 0 :(得分:27)
SimpleIoc根据您传递给它的键返回实例。如果在没有键的情况下调用GetInstance(),则始终会获得对象的默认实例。仅在第一次调用GetInstance时创建实例(延迟创建)。如果使用密钥调用GetInstance,我会查看注册表中是否已存在此命名实例。如果它还没有,我创建它然后我返回它。如果已经存在具有该密钥的实例,我只需将其返回。
在alpha版本(BL16 MIX版本)中,有一个错误导致Register在使用密钥时过早地创建实例。这个错误修复了V4 beta1,我将在本周发布。
正如您所看到的,如果您始终使用相同的密钥(或者根本不使用密钥,则只使用默认实例),您将从SimpleIoc获得相同的实例。
有意义吗? 劳伦
答案 1 :(得分:1)
我在正常的silverlight项目中使用Sterling,我正在做的就是将其添加到App.xaml ..
<Application.ApplicationLifetimeObjects>
<common:SterlingService />
<appServices:WebContext>
<appServices:WebContext.Authentication>
<!--<appsvc:FormsAuthentication/>-->
<appsvc:WindowsAuthentication />
</appServices:WebContext.Authentication>
</appServices:WebContext>
</Application.ApplicationLifetimeObjects>
我从例子中复制了SterlingService.cs的常用引用..就像这样开始
namespace Common
{
public sealed class SterlingService : IApplicationService, IApplicationLifetimeAware, IDisposable
{
public const long KILOBYTE = 1024;
public const long MEGABYTE = 1024 * KILOBYTE;
public const long QUOTA = 100 * MEGABYTE;
private SterlingEngine _engine;
private static readonly ISterlingDriver _driver = new IsolatedStorageDriver(); // could use this: new MemoryDriver();
public static SterlingService Current { get; private set; }
}
后来我刚刚创建了一个围绕这个服务的包装器,就像soo ..我只是调用SterlingService,我需要像这样引用服务......希望这会有所帮助。
[ExportService(ServiceType.Runtime, typeof(IOffLineDataService))]
public sealed class OfflineDataService : IOffLineDataService
{
User user = WebContext.Current.User;
public OfflineDataService()
{
}
public void PurgeAll(Action<Exception> callback)
{
try
{
SterlingService.Current.Database.Purge();
callback(null);
}
catch (Exception ex)
{
Error.LogError(ex, user);
callback(new Exception(ErrorMessages.OfflinePurgeAll));
}
}
}