简体   繁体   中英

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. Can this container be used to register an ILog factory that returns an ILog appropriate for the type in which it will reside?

Put another way, given the following 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)?

Put a third way, most succinctly, Can I use Funq.Container for ILog injection instead of LogManager?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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