1

ServiceStack AppHost 提供了一个 Funq.Container 用于注册可以在构造时注入到服务中的类型。这个容器是否可以用于注册一个 ILog 工厂,该工厂返回一个适合其所在类型的 ILog?

换句话说,给定以下 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
    }
}

和服务:

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

有什么我可以添加到 AppHost.Configure 以避免在我的所有服务中使用静态 ILog 样板的(而只是使用普通的旧 ILog 属性)?

第三种方式,最简洁地说,我可以使用 Funq.Container 进行 ILog 注入而不是 LogManager 吗?

4

1 回答 1

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

现在您的服务可能如下所示:

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

    public object Execute(FooRequest request)
    {
        Log.Info("Received request: " + request.Dump());
        return new FooResponse();
    }
}
于 2013-01-15T22:52:23.513 回答