【问题标题】:Autofac: How to inject IPrincipal into Repository layerAutofac:如何将 IPrincipal 注入存储库层
【发布时间】:2014-11-26 17:02:47
【问题描述】:

我正在使用 c#.net web api 和 Autofac DI 容器使用 Repository Layer/Service Layer/Presentation Layer 设计一个 n 层应用程序。这是我的困境。我正在尝试对我的 web api 控制器进行单元测试,但我的存储库对 IPrincipal 具有属性依赖关系,我想将其属性注入到我的存储库层中。我想创建一个 MockUser(IPrincipal) 并将这个对象注入我的存储库。这是我当前的层次结构,我的控制器是注入服务对象的构造函数,我的服务对象是注入我的存储库对象的构造函数。这部分似乎工作。但是由于某种原因,每次我运行测试时,我的 Principal 属性都是空的。请检查下面的代码,让我知道我做错了什么:

Repository Base Class:

protected IPrincipal Principal 
{
    get { return _principal; }
}


Autofac Config Static Method

public class AutofacConfig
{
    public static IContainer ConfigContainer()
    {
        var _builder = new ContainerBuilder();

        UserPrincipal principal = MemberFactory.GetTestUser();



        var _config = new HttpConfiguration();
        _builder.RegisterControllers(typeof(BillingController).Assembly);
        _builder.RegisterWebApiModelBinders(typeof(BillingController).Assembly);
        _builder.RegisterApiControllers(typeof(BillingController).Assembly);
        _builder.RegisterModelBinders(typeof(BillingController).Assembly);
        _builder.RegisterModelBinderProvider();
        _builder.RegisterModule(new AutofacWebTypesModule());

        _builder.RegisterSource(new ViewRegistrationSource());
        _builder.RegisterFilterProvider();
        _builder.RegisterWebApiFilterProvider(_config);

        //_builder.Register(x => principal).As<IPrincipal>().PropertiesAutowired();
        _builder.RegisterType<BillingRepository>().As<IBillingRepository>().PropertiesAutowired();
        _builder.RegisterType<UserPrincipal>().As<IPrincipal>().PropertiesAutowired();
        _builder.RegisterType<GroupRepository>().As<IGroupRepository>().PropertiesAutowired();
        _builder.RegisterType<BillingService>().As<IBillingService>().PropertiesAutowired();
        _builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
        _builder.Register(c => principal).As<IPrincipal>();

        var _container = _builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));

        // Create the depenedency resolver.
        var resolver = new AutofacWebApiDependencyResolver(_container);

        // Configure Web API with the dependency resolver.
        _config.DependencyResolver = resolver;

        return _container;
    }
}

Test Controller (Get Method)

[TestClass]
public class BillingControllerTest
{
   [TestMethod]
    public async Task Get()
    {
        var _container = AutofacConfig.ConfigContainer();

        var _controller = _container.Resolve<BillingController>();

        var _bodyCompRecords = await _controller.GetMyOutstandingBills(1, 10);

        Assert.IsNull(_bodyCompRecords);
        Assert.IsNull(_bodyCompRecords.BillingList);
        Assert.IsNull(_bodyCompRecords.CurrentPage);
        Assert.IsTrue(_bodyCompRecords.BillingList.Count > 0);
    }
}

【问题讨论】:

  • 您是如何在存储库中设置 IPrincipal 的?是构造函数注入的吗?
  • 这就是问题所在。我正在尝试使用上面的代码对其进行属性注入。
  • 您是否尝试为此属性添加protected set。我不确定autofac,但也许你应该用一些属性装饰这个属性,autoFac 知道这是一个可注入属性。
  • 尝试了受保护的设置器,但仍然无法正常工作。我认为我可能需要将对象实例注入属性的 Autofac 语法。根据我的阅读,Autofac 不需要任何属性。

标签: c# asp.net-web-api dependency-injection autofac


【解决方案1】:

您是否尝试为此属性添加受保护集?我不确定 autofac 但也许你应该用 autofac 的一些属性来装饰这个属性,因为 autofac 知道这是一个可注入的属性。

另一方面,.Net 应用程序中的所有线程都有一个主体。您可以在 Thread.CurrentPrincipal 静态属性上获取/设置它。您可以尝试设置一个自定义 Principal 并使您的属性产生它。

在你的单元测试设置中,你可以定义它,例如:

void Setup()
{
   IPrincipal principal = new GenericPrincipal(new GenericIdentity("userName"), new string[] { "role1", "role2" });
   Thread.CurrentPrincipal = principal;
}

在您的存储库中,您可以有一个属性来公开它,

protected IPrincipal Principal 
{
    get { return Thread.CurrentPrincipal; }
}

在 Web 应用程序 (asp.net webforms/mvc/web api) 中,您可以使用 HttpContext.Current.User 静态属性,因此,只需调用:

HttpContext.Current.User = principal;

作为一个好的做法,您可以同时设置HttpContext.Current.UserThread.CurrentPrincipal。请记住,Web API 是无状态的,因此,实现一个 http 模块以从 http 标头读取参数并将主体设置为您的应用程序。我不确定这是否是您的情况,但this article 显示了如何执行此操作。

http://www.asp.net/web-api/overview/security/basic-authentication

【讨论】:

  • 刚刚尝试过,效果很好。谢谢你。在使用 web api 时,如何保证在运行应用程序时正确设置 Thread.CurrentPrincipal。直播吗?
  • 问题:如何设置 Principal 的 IsUserAuthenticated 属性?
  • 这是另一个线程的问题,但是,看看表单身份验证。
  • Autofac 需要一个公共的 setter 来进行属性注入。
猜你喜欢
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多