Skip to content

Commit

Permalink
Building a new sample showing how to use various containers with Mass…
Browse files Browse the repository at this point in the history
…Transit
  • Loading branch information
phatboyg committed Jan 24, 2019
0 parents commit 91cbdd4
Show file tree
Hide file tree
Showing 14 changed files with 436 additions and 0 deletions.
63 changes: 63 additions & 0 deletions .gitignore
@@ -0,0 +1,63 @@
build_output/*
build_artifacts/*
build_temp/*
*.suo
*.user
packages
*.dotCover

*.ncrunch*
.vs

.fake

src/logs/*

**/*.sln*
bin
obj
_ReSharper*

*.csproj.user
*.resharper.user
*.resharper
*.ReSharper
*.cache
*~
*.swp
*.bak
*.orig

NuGet.exe
packages

# Tests
TestResult.xml
submit.xml
tests/*
SolutionVersion.cs
src/SolutionVersion.cs
tests
doc/build/*
*.[lm]df
*.runsettings

# osx noise
.DS_Store
*.DotSettings
/src/MassTransit.SimpleInjectorIntegration/MassTransit.SimpleInjectorIntegration.csproj.nuspec
*.DS_Store

_book
/node_modules
.vscode
**/.idea/
appsettings.Development.json

# Cake
tools/**
!tools/packages.config

# Artifacts
artifacts/**
artifacts_old/**
121 changes: 121 additions & 0 deletions Sample-Autofac/Program.cs
@@ -0,0 +1,121 @@
using System;
using System.Threading.Tasks;
using Autofac;
using GreenPipes;
using MassTransit;
using MassTransit.Saga;
using MassTransit.Util;
using Sample.Components;
using Sample.Contracts;

namespace Sample_Autofac
{
class Program
{
static void Main()
{
var container = ConfigureContainer();

var bus = container.Resolve<IBusControl>();

try
{
bus.Start();
try
{
Console.WriteLine("Bus started, type 'exit' to exit.");

bool running = true;
while (running)
{
var input = Console.ReadLine();
switch (input)
{
case "exit":
case "quit":
running = false;
break;

case "submit":
TaskUtil.Await(() => Submit(container));
break;
}
}
}
finally
{
bus.Stop();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}

static async Task Submit(IContainer container)
{
ISendEndpointProvider provider = container.Resolve<ISendEndpointProvider>();
var endpoint = await provider.GetSendEndpoint(new Uri("loopback://localhost/submit-order"));

await endpoint.Send<SubmitOrder>(new
{
OrderId = NewId.NextGuid(),
OrderDateTime = DateTimeOffset.Now
}, sendContext => sendContext.CorrelationId = NewId.NextGuid());
}

static IContainer ConfigureContainer()
{
var builder = new ContainerBuilder();

builder.RegisterConsumers(typeof(SubmitOrderConsumer).Assembly)
.InstancePerLifetimeScope();

builder.RegisterStateMachineSagas(typeof(OrderStateMachine).Assembly);
builder.RegisterType<PublishOrderEventActivity>();

builder.RegisterGeneric(typeof(InMemorySagaRepository<>))
.As(typeof(ISagaRepository<>));

builder.Register(BusFactory)
.As<IBusControl>()
.As<IBus>()
.As<ISendEndpointProvider>()
.As<IPublishEndpoint>()
.SingleInstance();

return builder.Build();
}

static IBusControl BusFactory(IComponentContext context)
{
return Bus.Factory.CreateUsingInMemory(cfg =>
{
cfg.ReceiveEndpoint("submit-order", e =>
{
e.UseMessageRetry(r => r.Interval(5, 1000));
e.UseInMemoryOutbox();
e.Consumer<SubmitOrderConsumer>(context);
});
cfg.ReceiveEndpoint("order-state", e =>
{
e.UseMessageRetry(r => r.Interval(5, 1000));
e.UseInMemoryOutbox();
e.StateMachineSaga<OrderState>(context);
});
cfg.ReceiveEndpoint("order-state-audit", e =>
{
e.UseMessageRetry(r => r.Interval(5, 1000));
e.UseInMemoryOutbox();
e.Consumer<OrderStateAuditConsumer>(context);
});
});
}
}
}
19 changes: 19 additions & 0 deletions Sample-Autofac/Sample-Autofac.csproj
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Sample_Autofac</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MassTransit" Version="5.2.3" />
<PackageReference Include="MassTransit.Autofac" Version="5.2.3" />
<PackageReference Include="MassTransit.Automatonymous.Autofac" Version="5.2.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Sample.Components\Sample.Components.csproj" />
</ItemGroup>

</Project>
28 changes: 28 additions & 0 deletions Sample-Containers.sln
@@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample-Autofac", "Sample-Autofac\Sample-Autofac.csproj", "{459F5E30-8F4A-4A0A-9E9E-D4F08180EA59}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.Contracts", "Sample.Contracts\Sample.Contracts.csproj", "{455F8888-B3CB-4467-B3E6-D3F6E0B3FBBC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.Components", "Sample.Components\Sample.Components.csproj", "{CF024BAF-1C16-4BA7-B323-350FC2EFA85B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{459F5E30-8F4A-4A0A-9E9E-D4F08180EA59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{459F5E30-8F4A-4A0A-9E9E-D4F08180EA59}.Debug|Any CPU.Build.0 = Debug|Any CPU
{459F5E30-8F4A-4A0A-9E9E-D4F08180EA59}.Release|Any CPU.ActiveCfg = Release|Any CPU
{459F5E30-8F4A-4A0A-9E9E-D4F08180EA59}.Release|Any CPU.Build.0 = Release|Any CPU
{455F8888-B3CB-4467-B3E6-D3F6E0B3FBBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{455F8888-B3CB-4467-B3E6-D3F6E0B3FBBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{455F8888-B3CB-4467-B3E6-D3F6E0B3FBBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{455F8888-B3CB-4467-B3E6-D3F6E0B3FBBC}.Release|Any CPU.Build.0 = Release|Any CPU
{CF024BAF-1C16-4BA7-B323-350FC2EFA85B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF024BAF-1C16-4BA7-B323-350FC2EFA85B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF024BAF-1C16-4BA7-B323-350FC2EFA85B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF024BAF-1C16-4BA7-B323-350FC2EFA85B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
15 changes: 15 additions & 0 deletions Sample.Components/OrderState.cs
@@ -0,0 +1,15 @@
using System;
using Automatonymous;

namespace Sample.Components
{
public class OrderState :
SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; }

public DateTimeOffset OrderSubmissionDateTime { get; set; }
public DateTime OrderSubmissionDateTimeUtc { get; set; }
}
}
16 changes: 16 additions & 0 deletions Sample.Components/OrderStateAuditConsumer.cs
@@ -0,0 +1,16 @@
using System;
using System.Threading.Tasks;
using MassTransit;
using Sample.Contracts;

namespace Sample.Components
{
public class OrderStateAuditConsumer :
IConsumer<OrderStateCreated>
{
public async Task Consume(ConsumeContext<OrderStateCreated> context)
{
await Console.Out.WriteLineAsync($"OrderState(created): {context.Message.OrderId} ({context.ConversationId})");
}
}
}
33 changes: 33 additions & 0 deletions Sample.Components/OrderStateMachine.cs
@@ -0,0 +1,33 @@
using System;
using Automatonymous;
using Sample.Contracts;

namespace Sample.Components
{
public class OrderStateMachine :
MassTransitStateMachine<OrderState>
{
public OrderStateMachine()
{
Event(() => OrderReceived, x => x.CorrelateById(m => m.Message.OrderId));

InstanceState(x => x.CurrentState);

Initially(
When(OrderReceived)
.ThenAsync(context => Console.Out.WriteLineAsync($"OrderState: Order Received: {context.Data.OrderId}"))
.Then((context) =>
{
context.Instance.OrderSubmissionDateTime = context.Data.OrderDateTime;
context.Instance.OrderSubmissionDateTimeUtc = context.Data.OrderDateTime.DateTime.ToUniversalTime();
})
.Activity(s => s.OfInstanceType<PublishOrderEventActivity>())
.TransitionTo(Submitted));
}

public Event<OrderReceived> OrderReceived { get; private set; }

public State Submitted { get; private set; }
public State Accepted { get; private set; }
}
}
70 changes: 70 additions & 0 deletions Sample.Components/PublishOrderEventActivity.cs
@@ -0,0 +1,70 @@
using System;
using System.Threading.Tasks;
using Automatonymous;
using GreenPipes;
using MassTransit;
using Sample.Contracts;

namespace Sample.Components
{
public class PublishOrderEventActivity :
Activity<OrderState>
{
readonly IPublishEndpoint _publishEndpoint;

public PublishOrderEventActivity(IPublishEndpoint publishEndpoint)
{
_publishEndpoint = publishEndpoint;
}

public void Probe(ProbeContext context)
{
context.CreateScope("publish-order-event");
}

public void Accept(StateMachineVisitor visitor)
{
visitor.Visit(this);
}

public async Task Execute(BehaviorContext<OrderState> context, Behavior<OrderState> next)
{
await Console.Out.WriteLineAsync(
$"Publishing Order Event Created: {context.Instance.CorrelationId} ({context.GetPayload<ConsumeContext>().ConversationId})");

await _publishEndpoint.Publish<OrderStateCreated>(new
{
OrderId = context.Instance.CorrelationId,
Timestamp = DateTime.UtcNow
}, sendContext => sendContext.CorrelationId = NewId.NextGuid());

await next.Execute(context);
}

public async Task Execute<T>(BehaviorContext<OrderState, T> context, Behavior<OrderState, T> next)
{
await Console.Out.WriteLineAsync(
$"Publishing Order Event Created: {context.Instance.CorrelationId} ({context.GetPayload<ConsumeContext>().ConversationId})");

await _publishEndpoint.Publish<OrderStateCreated>(new
{
OrderId = context.Instance.CorrelationId,
Timestamp = DateTime.UtcNow
}, sendContext => sendContext.CorrelationId = NewId.NextGuid());

await next.Execute(context);
}

public Task Faulted<TException>(BehaviorExceptionContext<OrderState, TException> context, Behavior<OrderState> next)
where TException : Exception
{
return next.Faulted(context);
}

public Task Faulted<T, TException>(BehaviorExceptionContext<OrderState, T, TException> context, Behavior<OrderState, T> next)
where TException : Exception
{
return next.Faulted(context);
}
}
}
16 changes: 16 additions & 0 deletions Sample.Components/Sample.Components.csproj
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MassTransit" Version="5.2.3" />
<PackageReference Include="MassTransit.Automatonymous" Version="5.2.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Sample.Contracts\Sample.Contracts.csproj" />
</ItemGroup>

</Project>

0 comments on commit 91cbdd4

Please sign in to comment.