MVVM Light SimpleIoC支持单例吗?



我在我当前的Windows Phone项目中使用SterlingDB,我希望能够使用MVVM Light v4中的新SimpleIoC容器从我的应用程序中的各个地方解决Sterling数据库。

但是,我不确定SimpleIoC是否支持注册单例。SterlingDB引擎应该只在应用程序第一次启动时创建,我不希望每次容器注入对它的引用时都启动新的实例。

如果有不同的方法来思考这个问题,我也很乐意考虑其他的方法。

SimpleIoc根据您传递给它的键返回实例。如果不带键调用GetInstance(),将始终获得对象的默认实例。实例只在第一次调用GetInstance时创建(惰性创建)。如果用一个键调用GetInstance,我会查找这个命名实例是否已经存在于注册表中。如果还没有,我创建它,然后返回它。如果已经存在一个实例,我就返回它。

在alpha版本(BL16 MIX版本)中,有一个bug导致Register过早地创建实例,当使用一个键时。我将在本周发布的V4测试版中修复此错误。

所以正如你所看到的,如果你总是使用相同的键,你将从SimpleIoc获得相同的实例(或者如果你根本不使用键,则只是默认实例)。

有意义吗?Laurent

我在我的正常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 fine我是从例子中复制过来的…像这样开始

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; }
}

之后我只是在这个服务周围创建了一个包装器,就像这样…我只要在需要引用服务的地方调用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));
            }
        }
}

最新更新