我正在尝试从 autofac 解析一个实例,它需要
Func<string>
作为构造函数参数。
构造函数:
public GitRepositoryFactory(
IGitCommands gitCommands,
Func<string> repositoryUrlRetriever)
{
_gitCommands = gitCommands;
_repositoryUrlRetriever = repositoryUrlRetriever;
}
我的注册:
var builder = new ContainerBuilder();
builder.RegisterModule<GitModule>();
builder.RegisterType<GitRepositoryFactory>().As<IGitRepositoryFactory>().WithParameter(
new TypedParameter(typeof(string), "https://bitbucket/scm/cmr/413.git"));
解决异常:
----> Autofac.Core.DependencyResolutionException : None of the constructors found on type 'IAI.Common.Utilities.Git.GitRepositoryFactory' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Func`1[System.String] repositoryUrlRetriever' of constructor 'Void .ctor(IAI.Common.Utilities.Git.IGitCommands, System.Func`1[System.String])'.
我在这里缺少什么?该字符串应该可以通过我提供的类型化参数来解析?
啊,在使用 autofac 多年之后,我想我仍在学习。对于其他遇到同样问题的人来说,事实证明我可以注册一个函数,但我需要明确提供
Func
作为对象。
我试过了
builder.RegisterType<GitRepositoryFactory>().As<IGitRepositoryFactory>().WithParameter(
new TypedParameter(typeof(Func<string>), () => "https://bitbucket/scm/cmr/413.git"));
它无法编译,但是当我显式地将对象实例化为
Func
时,它工作正常......
builder.RegisterType<GitRepositoryFactory>().As<IGitRepositoryFactory>().WithParameter(
new TypedParameter(typeof(Func<string>), new Func<string>(() => "https://bitbucket/scm/cmr/413.git")));