Autofac - 在运行时解析参数

时间:2018-06-17 04:36:39

标签: c# dependency-injection autofac

我有这个分层结构

namespace DataAccess 

public class SqlDataContext : ISqlDataContext
{
    public SqlDataContext(string connectionString)
    {
        _connectionFactory = CreateConnection(connectionString);
    }
}


namespace Repositories

public class UserRepository : IUserRepository
{
    public UserRepository(ISqlDataContext dataContext)
    {
        _db = dataContext;
    }
}

namespace Core

public class UserManager :IUserManager
{
    public UserManager(UserRepository repository)
   {
        _userRepository = repository;
    }
}

然后我在Autofac容器中注册这个

        builder.Register((a, b) => new SqlDataContext(b.Named<string>("connectionString")))
            .As<ISqlDataContext>()
            .InstancePerLifetimeScope();

        builder.RegisterType<UserRepository>()
            .As<IUserRepository>()
            .WithParameter((x, o) => x.Name == "dataContext", (x, o) => o.Resolve<ISqlDataContext>());

        builder.RegisterType<UserManager>()
            .As<IUserManager>()
            .WithParameter((x, o) => x.Name == "userRepository", (x, o) => o.Resolve<IUserRepository>());

然后我在我的客户端中调用它

      namespace Client

     internal void OnConnectionStringResolved() {

        var connectionString = GetConnectionString();

        var dbContext = DependencyResolver.Instance().Resolve<ISqlDataContext>(
            new NamedParameter("connectionString", connectionString)
            );

         var userRepository = 
             DependencyResolver.Instance().Resolve<IUserRepository>(
            new NamedParameter("dbContext", dbContext)
            );

        _userManager = DependencyResolver.Instance().Resolve<IUserManager>(
            new NamedParameter("userRepository", userRepository)
            );

       var user = _userManager.GetUser(userId);
     }

我不希望在我的客户端项目中引用DataAccess projet。但问题是ConnectionString只能在运行时解析。

我想在我的客户端调用应该是这样的

       _userManager = DependencyResolver.Instance().Resolve<IUserManager>(GetConnectionString());

有什么办法吗?

0 个答案:

没有答案