9

谁能指导我如何使用 Autofac 注册 RavenDB?

builder.Register<DocumentStore>(.. 之后呢?

4

1 回答 1

15

这是一个示例控制台程序,它不仅说明了如何连接文档存储,还说明了如何设置它,以便您可以注入您的文档会话:

using System.Threading.Tasks;
using Autofac;
using Raven.Client;
using Raven.Client.Document;

namespace ConsoleApplication1
{
  internal class Program
  {
    private static void Main()
    {
      var builder = new ContainerBuilder();

      // Register the document store as single instance,
      // initializing it on first use.
      builder.Register(x =>
        {
          var store = new DocumentStore { Url = "http://localhost:8080" };
          store.Initialize();
          return store;
        })
           .As<IDocumentStore>()
           .SingleInstance();

      // Register the session, opening a new session per lifetime scope.
      builder.Register(x => x.Resolve<IDocumentStore>().OpenSession())
           .As<IDocumentSession>()
           .InstancePerLifetimeScope()
           .OnRelease(x =>
             {
               // When the scope is released, save changes
               //  before disposing the session.
               x.SaveChanges();
               x.Dispose();
             });

      // Register other services as you see fit
      builder.RegisterType<OrderService>().As<IOrderService>();

      var container = builder.Build();


      // Simulate some activity.  5 users are placing orders simultaneously.
      Parallel.For(0, 5, i =>
        {
          // Each user gets their own scope.  In the real world this would be
          // a new inbound call, such as a web request, and you would let an
          // autofac plugin create the scope rather than creating it manually.
          using (var scope = container.BeginLifetimeScope())
          {
            // Let's do it.  Again, in the real world you would just inject
            // your service to something already wired up, like an MVC
            // controller.  Here, we will resolve the service manually.
            var orderService = scope.Resolve<IOrderService>();
            orderService.PlaceOrder();
          }
        });
    }
  }

  // Define the order service
  public interface IOrderService
  {
    void PlaceOrder();
  }

  public class OrderService : IOrderService
  {
    private readonly IDocumentSession _session;

    // Note how the session is being constructor injected
    public OrderService(IDocumentSession session)
    {
      _session = session;
    }

    public void PlaceOrder()
    {
      _session.Store(new Order { Description = "Stuff", Total = 100.00m });

      // we don't have to call .SaveChanges() here because we are doing it
      // globally for the lifetime scope of the session.
    }
  }

  // Just a sample of something to save into raven.
  public class Order
  {
    public string Id { get; set; }
    public string Description { get; set; }
    public decimal Total { get; set; }
  }
}

请注意, DocumentStore 是单个实例,但 DocumentSession 是每个生命周期范围内的实例。对于这个示例,我手动创建生命周期范围并并行执行,模拟 5 个不同的用户可能如何同时下订单。他们每个人都将获得自己的会话。

将 SaveChanges 放入 OnRelease 事件是可选的,但您不必将其放入每个服务中。

在现实世界中,这可能是 Web 应用程序或服务总线应用程序,在这种情况下,您的会话应分别限定为单个 Web 请求或消息的生命周期。

如果您使用的是 ASP.Net WebApi,您应该从 NuGet 获取 Autofac.WebApi 包并使用他们的 .InstancePerApiRequest() 方法,该方法会自动创建适当的生命周期范围。

于 2012-11-08T00:13:37.763 回答