Autofac:如何将IPrincipal注入Repository层

时间:2014-11-26 17:02:48

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

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

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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

在Unittest的设置中,您可以为样本定义它:

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

相关问题