简体   繁体   English

如何使用ServiceStack和Funq.Container解析ILog

[英]How can I resolve ILog using ServiceStack and Funq.Container

The ServiceStack AppHost provides a Funq.Container with which to register types that can be injected into Services as they are constructed. ServiceStack AppHost提供了Funq.Container,用于注册可在构造服务时注入到服务中的类型。 Can this container be used to register an ILog factory that returns an ILog appropriate for the type in which it will reside? 可以使用此容器注册一个ILog工厂,该工厂返回适合于其驻留类型的ILog吗?

Put another way, given the following AppHost: 换一种说法,给出以下AppHost:

public class AppHost : AppHostBase
{
    public AppHost() : base("Example Web Services", Assembly.GetExecutingAssembly())
    {
    }

    public override void Configure(Funq.Container container)
    {
        var baseLogFactory = new ServiceStack.Logging.NLogger.NLogFactory();
        LogManager.LogFactory = new ServiceStack.Logging.Elmah.ElmahLogFactory(baseLogFactory);
        // Would prefer to register a Func<Type, ILog> one time here
    }
}

And a Service: 和服务:

public class FooService : IService<FooRequest>
{
    static ILog Log { get { return LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); } }
    // Would prefer:
    // public ILog { get; set; }

    public object Execute(FooRequest request)
    {
        Log.Info("Received request: " + request.Dump());
        return new FooResponse();
    }
}

Is there anything I can add to AppHost.Configure to avoid the static ILog boilerplate in all of my Services (and instead just use a plain old ILog property)? 有什么我可以添加到AppHost.Configure的方法来避免我所有服务中的静态ILog模板(而是仅使用普通的旧ILog属性)?

Put a third way, most succinctly, Can I use Funq.Container for ILog injection instead of LogManager? 简而言之,我可以使用第三种方式来代替IManager使用Funq.Container进行ILog注入吗?

container.Register<ILog>(
    ctx => LogManager.LogFactory.GetLogger(typeof(IService))
);

Now your service could look like this: 现在您的服务可能如下所示:

public class FooService : IService<FooRequest>
{
    public ILog { get; set; }

    public object Execute(FooRequest request)
    {
        Log.Info("Received request: " + request.Dump());
        return new FooResponse();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM