3

如何在带有scan扩展名的程序集中注册所有接口,而不用在 ASP.NET Core 2 中全部分开?

在结构图中:

Scan(_ =>
{
    // Declare which assemblies to scan
    _.Assembly("StructureMap.Testing"); 

});

在 Scrutor 中:

collection.Scan(scan => scan
     // We start out with all types in the assembly of ITransientService
    .FromAssemblyOf<ITransientService>()
        // AddClasses starts out with all public, non-abstract types in this
        // assembly. These types are then filtered by the delegate passed to the
        // method. In this case, we filter out only the classes that are assignable
        // to ITransientService.
        .AddClasses(classes => classes.AssignableTo<ITransientService>())
            // We then specify what type we want to register these classes as.
            // In this case, we want to register the types as all of its implemented
            // interfaces. So if a type implements 3 interfaces; A, B, C, we'd end
            // up with three separate registrations.
            .AsImplementedInterfaces()
            // And lastly, we specify the lifetime of these registrations.
            .WithTransientLifetime()
        // Here we start again, with a new full set of classes from the assembly
        // above. This time, filtering out only the classes assignable to
        // IScopedService.
        .AddClasses(classes => classes.AssignableTo<IScopedService>())
            // Now, we just want to register these types as a single interface,
            // IScopedService.
            .As<IScopedService>()
            // And again, just specify the lifetime.
            .WithScopedLifetime());
4

2 回答 2

4

这将注册所有实现了一些接口的类,就像默认情况下 StructureMap 所做的那样:

services.Scan(scan => scan
    .FromAssemblyOf<IService>()
    .AddClasses()
    .AsImplementedInterfaces()
    .WithTransientLifetime());
于 2018-09-17T12:42:24.507 回答
0

对于所有类型的使用寿命,您可以定义

services.Scan(scan => scan
      .FromAssemblyOf<IApplicationService>()

      .AddClasses(classes => classes.AssignableTo<IScopedDependency>())
      .AsMatchingInterface()
      .WithScopedLifetime()

      .AddClasses(classes => classes.AssignableTo<ISingletonDependency>())
      .AsMatchingInterface()
      .WithSingletonLifetime()

      .AddClasses(classes => classes.AssignableTo<ITransientDependency>())
      .AsMatchingInterface()
      .WithTransientLifetime()
);

接口在哪里

public interface IApplicationService { }
public interface IScopedDependency { }
public interface ITransientDependency { }
public interface ISingletonDependency { }

并用于界面中的示例

public interface IUserService : IScopedDependency { }
public class UserService: IUserService { }
于 2019-12-14T20:35:12.563 回答