首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法解析通过程序集扫描注册的服务

无法解析通过程序集扫描注册的服务
EN

Stack Overflow用户
提问于 2020-02-14 13:40:58
回答 1查看 792关注 0票数 1

配置

我有:

(IMyRepository)

  • A
  • -- .net核心MVC应用程序项目
  • --一个包含
    • A控制器(MyController)、
    • A存储库接口
    • 的模块项目(MyRepository,实现IMyRepository和IRepository)

.net核心应用程序引用模块项目

我在MVC应用程序中使用Scrutor获取在任何引用项目中实现IRepositoy的所有类,并在服务集合中注册它们:

代码语言:javascript
复制
public static void RegisterAllTypes<T>(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{

    var entryAssembly = Assembly.GetEntryAssembly();
    var referencedAssemblies = entryAssembly.GetReferencedAssemblies().Select(Assembly.Load);
    var assemblies = new List<Assembly> { entryAssembly }.Concat(referencedAssemblies).ToArray();

    services.Scan(
        x =>
        {
            x.FromAssemblies(assemblies)
                .AddClasses(classes => classes.AssignableTo(typeof(T)))
                    .AsImplementedInterfaces()

                .WithLifetime(lifetime);
    });
}

问题

如果我检查服务集合,我可以看到IMyRepository已经注册,并且应该解析为MyRepository。但是,当将存储库注入到MyController中时,如下所示:

代码语言:javascript
复制
private readonly IMyRepository _myRepository ;

public MyController(IMyRepository myRepository )
{
    _myRepository = myRepository;
}

抛出错误:

无法解析“IMyRepository”类型的服务,同时试图激活“MyController”。

除非。

在通过Scrutor注册存储库之后,我将

代码语言:javascript
复制
var test = typeof(IMyRepository);

此时,一切都如预期的那样运作。但是,这完全违背了自动依赖注册的全部要点。

任何帮助都非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-14 23:31:02

更改了注册方法以使用FromApplicationDependencies(),现在一切似乎都好起来了。

代码语言:javascript
复制
public static void RegisterAllTypes<T>(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{
    services.Scan(
        x =>
        {
            x.FromApplicationDependencies()
                .AddClasses(classes => classes.AssignableTo(typeof(T)))
                    .AsImplementedInterfaces()
                    .WithLifetime(lifetime);
        });
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60227501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档