使用参数

时间:2018-04-18 23:54:32

标签: asp.net-core dependency-injection azure-service-fabric

我有一个Asp.net核心状态服务需要引用具有依赖注入的接口IUser。

IUser接口由UserRepository类实现:

    public class UserRepository : IUser
{
    private IMemoryCache _cache;
    private IUtility _utility;
    public UserRepository(IMemoryCache memoryCache, IUtility utility)
    {

        _cache = memoryCache;
        _utility = utility;
    }

    /// <summary>
    /// Find the User using the Internal ID
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="useCache"></param>
    /// <returns></returns>
    public async Task<ApplicationUser> FindByIdAsync(string Id, bool useCache = true)
    {
          //Find the user and use cache and utilities methods
    }
}

MyStateful.cs 文件中,我可以像在无状态服务中那样成功添加对构造函数的引用:

 internal sealed class MyStateful: StatefulService
{
    private readonly IUser _user;
    public MyStateful(StatefulServiceContext context, IUser user)
        : base(context)
    {
        _user = user;
    }

}

在Program.cs中我遇到了问题:

ServiceRuntime.RegisterServiceAsync("MyStatefulType",
context => new MyStateful(context, new UserRepository())).GetAwaiter().GetResult();

错误没有参数给出对应于所需的形式参数&#39; memoryCache&#39; UserRepository(IMemoryCache,IUtility)

在UserRepository中没有DI(使用无参数构造函数)它都可以工作,而在无状态服务中,我在 Startup.cs 文件中声明了最终依赖项,如:

 services.AddScoped<IUser, UserRepository>();

并在构造函数中处理所有内容。

我如何才能在状态服务中完成这项工作?

1 个答案:

答案 0 :(得分:1)

您可以使用Autofac.Integration.ServiceFabric。它是一个支持Service Fabric的Autofac扩展。在Program.cs中注册将如下所示:

    var builder = new ContainerBuilder();
    builder.RegisterServiceFabricSupport();
    builder.RegisterType<UserRepository>().As<IUser>();
    builder.RegisterStatefulService<MyStateful>("MyStatefulType");
    using (builder.Build())
    {
        Thread.Sleep(Timeout.Infinite);
    }

有关它的更多信息:https://alexmg.com/posts/introducing-the-autofac-integration-for-service-fabric