Skip to content
Joao Grassi edited this page Oct 6, 2019 · 10 revisions
var store = Wireup.Init()
  .UsingSqlPersistence("Name Of EventStore ConnectionString In Config File")
  .InitializeStorageEngine()
  .UsingJsonSerialization()
  .Compress()
  .EncryptWith(EncryptionKey)
  .HookIntoPipelineUsing(new[] { new AuthorizationPipelineHook() })
  /* DIspatcher has been removed in NEventStore 6.x
  .UsingAsynchronousDispatchScheduler()
  // Example of NServiceBus dispatcher: https://gist.github.com/1311195
  .DispatchTo(new My_NServiceBus_Or_MassTransit_OrEven_WCF_Adapter_Code())
  */
  .Build();		

// Write and Read Single Streams
using (store)
{
  // some business code here
  using (var stream = store.CreateStream(myMessage.CustomerId))
  {
    stream.Add(new EventMessage { Body = myMessage });
    stream.CommitChanges(myMessage.MessageId);
  }
  
  using (var stream = store.OpenStream(myMessage.CustomerId, 0, int.MaxValue))
  {
    foreach (var @event in stream.CommittedEvents)
    {
      // business processing...
    }
  }
}

// Read the Store with a Polling Client
using (store)
{
  Int64 checkpointToken = LoadCheckpoint();
  var client = new PollingClient2(store.Advanced, commit =>
  {
    // Project / Dispatch the commit etc
    Console.WriteLine(Resources.CommitInfo, commit.BucketId, commit.StreamId, commit.CommitSequence);
    // Track the most recent checkpoint
    checkpointToken = commit.CheckpointToken;
    return PollingClient2.HandlingResult.MoveToNext;
  },
  waitInterval: 3000);
  // start the polling client
  client.StartFrom(checkpointToken);
  // before terminating the execution...
  client.Stop();
  SaveCheckpoint(checkpointToken);
}

If you are using an inversion of control container, registering the store as Single Instance should be safe, as it is designed to be thread-safe (see IStoreEvents).

The Streams that can be opened from the store (calling CreateStream() or OpenStream()) are not thread-safe (see IEventStream).

For a more complete example, please see NEventStore.Example and NEventStore.PollingClientExample.

A quick explanation of some of the Wireup options

  • LogToOutputWindow()

    Turns on logging to the debugger's "Output" window (using Trace.WriteLine). Alternatives are LogToConsoleWindow or simply LogTo, which you can use to implement your own logging or wire your preferred logging framework.|

  • UsingInMemoryPersistence()

    Makes NEventStore use an in-memory data store, useful for testing.

  • UsingSqlPersistence("EventStore")

    Makes NEventStore use the SQL persistence engine. As usual, the connection string is by default read from the app.config or web.config; you can also supply your own IConnectionFactory.

  • WithDialect(new MsSqlDialect())

    Enables the SQL persistence engine to use MSFT SQL Server.

  • WithStreamIdHasher(s => s)

    Defines a different Stream ID hashing algorithm.

    The SQL persistence engine stores stream IDs in two different forms: the long, original one (with up to 1000 characters), and a shortened, "hashed" one (with up to 40 characters). The shortened one is used to implement efficient, indexed access in SQL Server. By default, SHA-1 indexing is used for hashing.

    If the used stream IDs aren't longer than 40 characters (e.g., if they are string-converted Guids), an identity hashing algorithm can be supplied (s => s). This makes the stored Stream IDs human-readable.

  • EnlistInAmbientTransaction()

    Enables two-phase commit. By default, NEventStore will suppress surrounding TransactionScopes so that all of its operations run in a dedicated, separate transaction. This option changes the behavior so that NEventStore enlists in a surrounding TransactionScope, if there is any.

    Do not use this unless you really need it - the default is to not enlist in ambient transactions.

    Note that this option has undesired side effects that you might need to work around, at least with the SQL Persistence: https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/12 and https://github.com/NEventStore/NEventStore/issues/414.

  • InitializeStorageEngine()

    Causes the persistence engine to initialize its schema. E.g., the SQL persistence engine with the MsSqlDialect will execute something like this:

    IF EXISTS(SELECT * FROM sysobjects WHERE name='Commits' AND xtype = 'U') RETURN; CREATE TABLE [dbo].[Commits] ...

  • TrackPerformanceInstance("instanceName")

    Not available in .NET Core

    This enables NEventStore performance counters with the given instance name. E.g., "Total commits", "Commits/s", etc.

  • UsingJsonSerialization()

    Makes NEventStore serialize your events using JSON.NET. Alternatives are UsingBinarySerialization, UsingBsonSerialization, or custom serialization.

  • Compress()

    Enables Gzip compression of serialized event data.

  • EncryptWith(EncryptionKey)

    Enables encryption of serialized event data using the RijndaelManaged BCL class and the given key.

  • HookIntoPipelineUsing(new[] {new AuthorizationPipelineHook()})

    Represents an extension point into NEventStore, e.g., to intercept commits, execute actions before and after each commit is persisted to the underlying store, etc; e.g., to check whether the current user is authorized to read or write a specific stream.

  • PollingClient2

    A Reference implementation for a Polling Client used to 'listen' for new commits being written on the store; the commits are retrieved and passed to a callback function you can implement to process the events any way you want. See the Polling Client Example.

Obsolete

NEventStore 5.x

  • UsingSynchronousDispatchScheduler(), DispatchTo(new DelegateMessageDispatcher(DispatchCommit))

    Configures how events will be "dispatched" to "the event bus". Alternative is "UsingAsynchronousDispatchScheduler". This is deprecated and should no longer be used because it:

    • assumes a single receiver,
    • doesn't support read model catch-up, and
    • doesn't ensure event ordering during dispatch (requiring the receiver to resequence messages).

    See the issue #360 for more details.

    Use Polling Client instead, which solves these issues.