MVVMCross动态构造泛型IMvxLog<T>用于依赖注入

MVVMCross dynamically construct generic IMvxLog<T> for dependency injection

我正在尝试让 Mvx 以与 Microsoft Logging 相同的方式工作,例如ILogger<T> 通过注入但卡住了。

我扩展了界面:

public interface IMvxLog<T> : IMvxLog {

}

在我的 LoginViewModel 中,我想注入这个:

public LoginViewModel(IMvxLog<LoginViewModel> loggger) { }

然后我想我可以通过在 App.cs 中使用以下内容来动态构建:

var logProvider = Mvx.IoCProvider.Resolve<IMvxLogProvider>();
Mvx.IoCProvider.LazyConstructAndRegisterSingleton(typeof(IMvxLog<>), () => logProvider.GetLogFor<>());

它不起作用,因为我没有要传递给委托的类型参数。

Using the generic method group 'GetLogFor' requires 1 type arguments

如何做到这一点?

不允许您在那里做的事情,Mvx 可以注册此类注入的方式是使用开放泛型 typeof(IFoo<>)

您可以通过将提供程序 GetLogFor 包装在 MvxLog<T> 实现中并在其中调用相同的方法来做您想做的事:

public interface IMvxLog<T> : IMvxLog
{
}

public class MvxLog<T> : IMvxLog<T>
{
    private readonly IMvxLog _logImplementation;

    public MvxLog(IMvxLogProvider provider)
    {
        _logImplementation = provider.GetLogFor<T>();
    }

    public bool IsLogLevelEnabled(MvxLogLevel logLevel)
    {
        return _logImplementation.IsLogLevelEnabled(logLevel);
    }

    public bool Log(MvxLogLevel logLevel, Func<string> messageFunc, Exception exception = null, params object[] formatParameters)
    {
        return _logImplementation.Log(logLevel, messageFunc, exception, formatParameters);
    }
}

然后您只需注册它:

Mvx.IoCProvider.RegisterType(typeof(IMvxLog<>), typeof(MvxLog<>));

并像这样使用它:

public LoginViewModel(IMvxLog<LoginViewModel> loggger) 
{ 
    _logger = logger;    
}