Search code examples
c#wpfmvvmmvvm-lightsimpleioc

MVVM Light SimpleIoC can't find instance


I'm using WPF MVVM Light SimpleIoC to implement access to my services. I don't have any problems with registering and using my VM but when I register a service, I can't use It.

There is my code:

public interface IDeviceDataAccessService
{
    List<Models.Device> GetDevices();
    bool InsertDevice(ref Models.Device device, int userId);
    bool RemoveDevice(Models.Device device);
}

Implementation:

public class DeviceDataAccessService : DataAccesBase, IDeviceDataAccessService
{

    public DeviceDataAccessService(string connectionString) : base(connectionString)
    {
    }
    ...
}

ViewModelLocator

SimpleIoc.Default.Register<IDeviceDataAccessService, DeviceDataAccessService>();

And use in code

SimpleIoc.Default.GetInstance<IDeviceDataAccessService>();

When I change IDeviceDataAccessService for `TestViewModel' I don;t have any problems. But I can't use my service.

Message = "Exception has been thrown by the target of an invocation."

 at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] 
 arguments, Signature sig, Boolean constructor)\r\n  
 at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, 
 Object[] parameters, Object[] arguments)\r\n  
 at System.Delegate.DynamicInvokeImpl(Object[] args)\r\n  
 at GalaSoft.MvvmLight.Ioc.SimpleIoc.DoGetService(Type serviceType, String 
 key, Boolean cache) in C:\\Users\\lbugn\\Documents\\MVVMLight\\GalaSoft.MvvmLight\\GalaSoft.MvvmLight.Extras (PCL)\\Ioc\\SimpleIoc.cs:line 622\r\n   
 at GalaSoft.MvvmLight.Ioc.SimpleIoc.GetInstance[TService]() in C:\\Users\\lbugn\\Documents\\MVVMLight\\GalaSoft.MvvmLight\\GalaSoft.MvvmLight.Extras (PCL)\\Ioc\\SimpleIoc.cs:line 1059\r\n   
 at LabDesk.ViewModel.MainViewModel..ctor() in C:\\Users\\kzrostek\\Documents\\Git repo\\labdesk\\LabDESK\\LabDesk\\ViewModel\\MainViewModel.cs:line 141"

InnerException

{"Type not found in cache: System.String."}

Solution

  • I forget how you'd register connectionstring but I think what your error is saying is that the constructor of deviceaccesservice:

    public DeviceDataAccessService(string connectionString) 
    

    Expects a connection string as a parameter. It doesn't have that to give it so...crash. I think you need something more like:

    SimpleIoc.Default.Register<IDeviceDataAccessService>(() => {
        return new DeviceDataAccessService("Whatever connectionstring should be");
    });