Autofac运行参数 [英] Autofac runtime parameters

查看:273
本文介绍了Autofac运行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来autofac并期待看到通过运行值来构造的最佳实践。我读了一堆这何处问,但没有一个是完全充实计算器的问题。我们应该使用委托,工厂创建服务等等。我知道周围路过的容器没有做到这一点的最好办法。

I'm new to autofac and looking to see the best practices on passing runtime values to constructor. I've read a bunch of stackoverflow questions where this is asked but none are fully fleshed out. Should we be using delegates, factory to create service etc. I know passing the container around is not the best way to accomplish this.

在我的具体情况我有一个服务该访问多个依赖,说记录,数据提供器等。随着传递的一些服务,我需要捕捉我也有运行时的参数,用户ID说,密码。该用户名和密码所需的SomeService并抬头当Web浏览器执行特定的操作。 。下面是我和突出的问题。

In my particular case I have a service that access multiple dependencies, say logging, dataprovider, etc. Along with the few services being passed I also have run-time parameters I need to capture, say userid, password. The userid and password are required for the SomeService and are looked up when a web viewer performs a particular action. Below is what I have and highlighted is the issue.

public class SomeService : ISomeService
{
    private readonly IDataProvider _dataProvider;
    private readonly ILog _log;
    private readonly string _username;  
    private readonly string _password;

    public SomeService(IDataProvider dataProvider, ILog log,
        string username, string password)
    {
      _dataProvider = dataProvider;
      _log = log;
      _username = username;
      _password = password;
    }
}



dataProvider中,并记录在autofac

The dataprovider, and log are configured in autofac

builder.RegisterType<DataProviderService>().As<IDataProvider>()
builder.RegisterType<SomeLogService>().As<ILog>()

这其中大部分SomeService的功能需要用户名和密码之前执行的任务验证,因此想它最好的创造,但从来没有处理与autofac运行时间的要求时,传递到构造函数。我查看了问题​​ Autofac - 解决运行参数,而不有传容器周围,似乎接近我的需要,但需要的最佳方式了一些更多的反馈来实现。

Most of the functionality of this "SomeService" requires a username and password to verify before performing tasks, so figured it best to pass into constructor when creating but have never dealt with run-time requirements for autofac. I've reviewed the question Autofac - resolving runtime parameters without having to pass container around and it seems close to what I need but need some more feedback on the best way to accomplish this.

推荐答案

一般来说,你应该避免传递运行值到构造函数。这将复杂化你的设计,你的DI配置了很多。构造函数是依赖和配置值。无论是通过方法参数传递运行值或注入一个服务,它允许您检索的运行值。就拿一个允许检索登录的用户名电流的 IUserContext 服务。

In general you should prevent passing runtime values into constructors. That will complicate your design and your DI configuration a lot. Constructors are for dependencies and configuration values. Pass runtime values either through method arguments or inject a service that allows you to retrieve those runtime values. Take for instance an IUserContext service that allows retrieving the name current logged in user.

这篇关于Autofac运行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆