I'd like to track my messages using built-in interface CorrelatedBy<TKey>, but i didn't quite understand: should i initialize it myself, for example, in constructor of my message (command)?
public class RegisterCallback : IRegisterCallback
{
public RegisterCallback()
{
CorrelationId = Guid.NewGuid();
}
public Guid RequestId { get; set; }
public Guid CorrelationId { get; }
}
You should initialize it by either passing it into the constructor, or otherwise generating it as part of the constructor.
public RegisterCallback(Guid correlationId) {...}
Or you can generate it using NewId to get an ordered identifier.
public RegisterCallback()
{
CorrelationId = NewId.NextGuid();
}
Also, your interface should include CorrelatedBy<Guid> if you want to use the built-in support.
public interface IRegisterCallback :
CorrelatedBy<Guid> {...}
Related
Full code (github)...
I'm moving from MediatR to MassTransit to publish my domain events to a queue.
I'm using an interface IDomainEvent in different domain events that implement such interface (in this case PersonCreated and PersonPositionCreated). Then I have an entity 'Person' with a list of IDomainEvent in which I register all the domain events occurred. I Also have a consumer for each specific event.
After persist my entity, I want to iterate all the events of the entity and publish them to the queue.
// Event interface.
public class IDomainEvent
{
}
// Events.
public class PersonCreated : IDomainEvent
{
public int Id { get; set; }
}
public class PersonPositionCreated : IDomainEvent
{
public string Position { get; set; }
}
// Entity.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public List<IDomainEvent> Events { get; set; };
}
// Consumers.
public class PersonCreatedConsumer : IConsumer<PersonCreated>
{
public Task Consume(ConsumeContext<PersonCreated> context)
{
Debug.Print(context.Message.Id.ToString());
return Task.CompletedTask;
}
}
public class PersonPositionCreatedConsumer : IConsumer<PersonPositionCreated>
{
public Task Consume(ConsumeContext<PersonPositionCreated> context)
{
Debug.Print(context.Message.Position);
return Task.CompletedTask;
}
}
// My command.
//...
// Creates Person.
Person person = new Person(){ Id = 1, Name = "Alice", Position = "Developer" };
// Registers the events to the list.
person.Events.Add(new PersonCreated() { Id = person.Id });
person.Events.Add(new PersonPositionCreated() { Position = person.Position });
foreach (IDomainEvent personEvent in person.Events)
{
// This way, it publish an IDomainEvent and I don't want to use a IConsumer<IDoaminEvent> because I need specific consumers.
// How can I tell the bus that I sending the specific event and not the IDomainEvent?
//(I know that inside the iteration I'm dealing with IDomainEvent but it have access to the class that implement the interface).
// NOTE: That way works with MediatR specific handlers.
| |
\ /
\ /
\/
_bus.Publish(personEvent);
}
// Of course this two lines works!
//_bus.Publish<PersonCreated>(new PersonCreated() { Id = 1 });
//_bus.Publish<PersonPositionCreated>(new PersonPositionCreated() { Position = "Developer" });
//...
How can I tell the bus that I am sending the specific event and not the IDomainEvent?
(I know that inside the iteration I'm dealing with IDomainEvent, but it has access to the class that implement the interface).
You should call:
_bus.Publish((object)personEvent);
By casting it to an object, MassTransit will call GetType() and then publish to the exchange (and ultimately consumer) for the object type (aka, implemented message type).
I've been spinning my wheels trying to get the MassTransitStateMachine working and I seem to not understand exactly how this is supposed to work.
The error I'm receiving (full code below) is PayloadNotFoundException when I attempt to call stateMachine.RaiseEvent(instance, stateMachine.DeployApplicationRequest, request) combined with the .Send() Activity in the state machine. I've been trying to trace this through but have gotten nowhere.
Here's the relevant code and explanation of intent:
I receive a request to deploy an application via a webAPI post, and convert the request to a DeployApplicationRequest.
public record DeployApplicationRequest
{
// State machine properties
public Guid CorrelationId { get; init; }
public ChatApplication ChatApplication { get; init; }
public string ChannelId { get; init; }
public string UserId { get; init; }
// Command
public DeployApplication DeployApplication { get; init; }
}
public enum ChatApplication
{
Slack,
Teams
}
This request encapsulates two things: The state that the API needs to maintain so it knows how to route the results back to the requester (state machine properties) and the Command to be sent to the service bus.
The command, DeployApplication, looks like this:
public record DeployApplication
{
public Guid CorrelationId { get; init;}
public string InitiatedBy { get; init; }
public DateTime CreatedDate { get; init; }
public string Environment { get; init; }
public string PullRequestId { get; init; }
}
I have created a state instance to preserve the details of the request (such as whether it came in via Slack or Teams). I do not want to publish this information to the bus:
public class DeployApplicationState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; }
public ChatApplication ChatApplication { get; set; }
public string ChannelId { get; set; }
public string UserId { get; set; }
}
And I have created a StateMachine to handle this:
public class DeployApplicationStateMachine : MassTransitStateMachine<DeployApplicationState>
{
private readonly ILogger<DeployApplicationStateMachine> logger;
public DeployApplicationStateMachine(ILogger<DeployApplicationStateMachine> logger)
{
this.logger = logger;
InstanceState(x => x.CurrentState);
Event(() => DeployApplicationRequest, x => x.CorrelateById(context => context.Message.CorrelationId));
Initially(
When(DeployApplicationRequest)
.Then(x => {
x.Instance.CorrelationId = x.Data.CorrelationId;
x.Instance.ChannelId = x.Data.ChannelId;
x.Instance.ChatApplication = x.Data.ChatApplication;
x.Instance.UserId = x.Data.UserId;
})
.Send(context => context.Init<DeployApplication>(context.Data.DeployApplication))
.TransitionTo(Submitted));
}
public Event<DeployApplicationRequest> DeployApplicationRequest { get; private set; }
public State Submitted { get; private set; }
}
To trigger the initial event (since the request is not coming in via a Consumer but rather through a controller), I have injected the state machine into the MassTransit client, and I'm calling the RaiseEvent method:
public class MassTransitDeployClient : IDeployClient
{
private readonly DeployApplicationStateMachine stateMachine;
public MassTransitDeployClient(DeployApplicationStateMachine stateMachine)
{
this.stateMachine = stateMachine;
}
public async Task Send(DeployApplicationRequest request)
{
var instance = new DeployApplicationState
{
CorrelationId = request.CorrelationId,
ChannelId = request.ChannelId,
ChatApplication = request.ChatApplication,
UserId = request.UserId
};
await stateMachine.RaiseEvent(instance, stateMachine.DeployApplicationRequest, request);
// This works for sending to the bus, but I lose the state information
//await sendEndpointProvider.Send(request.DeployApplication);
}
}
And the container configuration is as follows:
services.AddMassTransit(x =>
{
x.AddSagaStateMachine<DeployApplicationStateMachine, DeployApplicationState>()
.InMemoryRepository();
x.UsingInMemory((context, cfg) =>
{
cfg.ConfigureEndpoints(context);
});
});
EndpointConvention.Map<DeployApplication>(new Uri($"queue:{typeof(DeployApplication).FullName}"));
services.AddMassTransitHostedService();
Raising the event works just fine, and the state machine transfers to Submitted successfully if I do not include .Send(...) in the state machine. The second I introduce that Activity I get the PayloadNotFoundException. I've tried about 15 different ways of doing this over the weekend with no success, and I'm hoping someone may be able to help me see the error of my ways.
Thanks for reading! Fantastic library, by the way. I'll be looking for ways to contribute to this going forward, this is one of the most useful libraries I've come across (and Chris your Youtube videos are excellent).
Saga state machines are not meant to be invoked directly from controllers. You should send (or publish) a message that will then be dispatched to the saga via the message broker.
IF you want to do it that way, you can use MassTransit Mediator instead, but you'll still be sending a message via Mediator to the saga, which will then be handled by MassTransit.
TL;DR - you don't use RaiseEvent with saga state machines.
Simplified example:
I have a custom plugin ICustomPlugin
public interface ICustomPlugin : IPlugin
{
}
and two implementations which require information from different configs. (Of course this only makes sense if the interface would define some common API but let's keep it simple)
public class CustomPluginWithConfigA : ICustomPlugin
{
}
public class CustomPluginWithConfigB: ICustomPlugin
{
}
Since I want to use both implementations my ModuleController should start both of them
[ServerModule(ModuleName)]
public class ModuleController : ServerModuleBase<ModuleConfig>
{
...
protected override void OnStart()
{
foreach (var converter in Container.ResolveAll<ICustomPlugin>())
converter.Start();
}
...
}
Now, what is the clean way to get only the config information that each implementation needs into the respective classes CustomPluginWithConfigA and CustomPluginWithConfigB?
Referencing the classes in the controller or providing the same config to all implementations feels equaly wrong to me.
You have several options and it depends whether your implementations CustomPluginA and CustomPluginB are located within the module, e.g. they are fixed components rather than flexible plugins, or loaded from additional MORYX packages.
In the first scenario you can simply add your components configuration values to the ModuleConfig and inject the config into your plugin, because a modules config is registered in its local container by default.
// In the module config
[DataMember]
public int ValueForA { get; set; }
[DataMember]
public string ValueForB { get; set; }
// In CustomPluginA: Injected
public ModuleConfig Config { get; set; }
public void SomeMethod()
{
var a = Config.ValueForA;
}
If on the other hand your plugins are fully located outside your module or can be extended with external implementations, you should use IConfiguredPlugin<TConfig> for your plugins and define a plugin base config. You will then instantiate your plugins with a factory passing their dedicated configs until we implement MORYX-Platform#10.
public class MyPluginConfig : IPluginConfig
{
[DataMember, PluginNameSelector(typeof(ICustomPlugin))]
public virtual string PluginName { get; set; }
[DataMember]
public int ValueForA { get; set; }
}
public interface ICustomPlugin : IConfiguredPlugin<MyPluginConfig>
{
}
[PluginFactory(typeof(IConfigBasedComponentSelector))]
public interface ICustomPluginFactory
{
ICustomPlugin Create(MyPluginConfig config);
}
// In your module config
[DataMember, PluginConfigs(typeof(ICustomPlugin))]
public List<MyPluginConfig> ConfiguredPlugins { get; set; }
// In your plugin
public class CustomConfigA : MyPluginConfig
{
public override PluginName { get { return nameof(CustomPluginA); } set { } }
}
[ExpectedConfig(typeof(CustomConfigA)]
[Plugin(LifeCycle.Transient, typeof(ICustomPlugin), Name = nameof(CustomPluginA))]
public class CustomPluginA : ICustomPlugin
{
public void Initialize(MyPluginConfig config)
{
var typed = (CustomPluginConfigA)config; // MORYX takes care of correct type
}
}
// In your controller Initialize
Container.LoadComponents<ICustomPlugin>(); // Load from all DLLs and packages
// In Start
var factory = Container.Resolve<ICustomPluginFactory>();
foreach (var config = Config.ConfiguredPlugins)
{
var plugin = factory.Create(config); // Calls Initialize with the config
}
Hope that answers your question.
I am a newbie to with unity and unit of work pattern and I am trying to write a code, which connects to my webservice and does all the work.
Everything goes well until I use the Database but I get lost when I try to use the webservice.
I have wasted my 2 precious days, searching every single possible article related to it and applying it to my code, but no luck till date.
I know, by writing connection string to web.config and calling it in dbcontext class controller will connect to the required database, but I am not connecting to any database, so what changes I need to do in web/app.config. Also, even if I write my connection logic in dbcontext constructor, it still searches and fills the dbcontext with sql server details. I presume thats happening because I am using DBSet.
Guys, you are requested to have a look at my code, I have done and show me some hope that I can do it. Let me know, if you want any other info related to the code that you want to see.
thanks
DBCONTEXT
public class CVSContext : DbContext
{
public DbSet<CVSViewModel> CVS { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Account> Accounts { get; set; }
public CVSContext()
{
//CRM Start
var clientCredentials = new System.ServiceModel.Description.ClientCredentials();
clientCredentials.UserName.UserName = "";
clientCredentials.UserName.Password = "";
var serviceProxy = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(new Uri("http://Organization.svc"), null, clientCredentials, null);
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
HttpContext.Current.Session.Add("ServiceProxy", serviceProxy);
//CRM End
}
}
GENERIC REPOSITORY
public class GenericRepository<TEntity> where TEntity : class
{
internal CVSContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(CVSContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
}
UNIT OF WORK
public interface IUnitOfWork : IDisposable
{
int SaveChanges();
}
public interface IDALContext : IUnitOfWork
{
ICVSRepository CVS { get; set; }
IContactRepository Contacts { get; set; }
//IAccountRepository Accounts { get; set; }
}
public class DALContext : IDALContext
{
private CVSContext dbContext;
private ICVSRepository cvs;
private IContactRepository contacts;
// private IAccountRepository accounts;
public DALContext()
{
dbContext = new CVSContext();
}
public ICVSRepository CVS
{
get
{
if (cvs == null)
cvs = new CVSRepository(dbContext);
return cvs;
}
set
{
if (cvs == value)
cvs = value;
}
}
public IContactRepository Contacts
{
get
{
if (contacts == null)
contacts = new ContactRepository(dbContext);
return contacts;
}
set
{
if (contacts == value)
contacts = value;
}
}
public int SaveChanges()
{
return this.SaveChanges();
}
public void Dispose()
{
if(contacts != null)
contacts.Dispose();
//if(accounts != null)
// accounts.Dispose();
if(dbContext != null)
dbContext.Dispose();
GC.SuppressFinalize(this);
}
}
SERVICE
public interface ICVSService
{
Contact CreateContact(Guid contactName, string productName, int price);
List<CVSViewModel> GetCVS();
List<Contact> GetContacts();
List<Account> GetAccounts();
}
public class CVSService : ICVSService, IDisposable
{
private IDALContext context;
public CVSService(IDALContext dal)
{
context = dal;
}
public List<CVSViewModel> GetCVS()
{
return context.CVS.All().ToList();
}
public List<Contact> GetContacts()
{
return context.Contacts.All().ToList();
}
public List<Account> GetAccounts()
{
return context.Accounts.All().ToList();
}
public Contact CreateContact(Guid contactName, string accountName, int price)
{
var contact = new Contact() { ContactId = contactName };
var account = new Account() { ContactName = accountName, Rent = price, Contact = contact };
//context.Contacts.Create(contact);
context.SaveChanges();
return contact;
}
public void Dispose()
{
if (context != null)
context.Dispose();
}
}
CONTROLLER
public ActionResult Index()
{
ViewData.Model = service.GetContacts();
return View();
}
It's all about proper abstractions. The common abstraction that is used between some data source (could be a db or ws) is the Repository pattern, or at a higher level the Unit of Work pattern. In fact Entity Framework DbContext is an implementation of the Unit of Work pattern, but it is tailored for databases. You can't use to communicate with a web service.
In that case you will have to write your own IRepository<T> abstraction and have a database specific implementation that uses a DbContext under the covers and a web service specific implementation that wraps a web service client proxy under the covers.
However, when your application gets more complex, you often find yourself wanting to have some sort of transaction like behavior. This is what the Unit of Work pattern if for: it presents a business transaction. Using the unit of work pattern to wrap multiple WS calls however, will get painful very soon. It's a lot of work to get right and in that case you will be much better of using a message based architecture.
With a message based architecture you define a single atomic operation (a business transaction or use case) as a specific message, for instance:
public class MoveCustomerCommand
{
public int CustomerId { get; set; }
public Address NewAddress { get; set; }
}
This is just an object (DTO) with a set of properties, but without behavior. Nice about this is that you can pass these kinds of objects over the wire using WCF or any other technology or process them locally without the need for the consumer to know.
Take a look at this article that describes it in detail. This article builds on top of that model and describes how you can write highly maintainable WCF services using this model.
Please can someone help me because I am getting confused.
I have an Entity like this:
public class Code
{
public int ID { get; set; }
public int UserID { get; set; }
public string CodeText { get; set; }
}
and an Interface like this:
public interface ICodeRepository
{
IQueryable<Code> Codes { get; }
void AddCode(Code code);
void RemoveCode(Code code);
Code GetCodeById(int id);
}
and a Repository like this:
public class SQLCodeRepository : ICodeRepository
{
private EFSQLContext context;
public SQLCodeRepository()
{
context = new EFSQLContext();
}
public IQueryable<Code> Codes
{
get { return context.Codes; }
}
public void AddCode(Code code)
{
context.Codes.Add(code);
context.SaveChanges();
}
public void RemoveCode(Code code)
{
context.Codes.Remove(code);
context.SaveChanges();
}
public Code GetCodeById(int id)
{
return context.Codes.Where(x => x.ID == id).FirstOrDefault();
}
}
and a Context like this:
public class EFSQLContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Code> Codes { get; set; }
public DbSet<PortfolioUser> PortfolioUsers { get; set; }
}
If I declare my controller like this:
public class SearchController : Controller
{
private ICodeRepository cRepo;
public SearchController(ICodeRepository codeRepository)
{
cRepo = codeRepository;
}
}
and then try to do cRepo.GetCodeById(1) nothing happens. But if I declare private ICodeRepository rep = new SQLCodeRepository and then call rep.GetCodeById(1) I can see the method in the Repository being called.
What am I doing wrong?
It looks like from the constructor signature, you are going to be doing some dependency injection. The step you are missing is to set up a DI container using a tool like Castle Windsor. You then configure the MVC resolver to use the DI container to give you the correct implementation of ICodeRepository.
See this
You'll need to create a resolver that implements IDependencyResolver and IDependencyScope and a controller factory that inheritsDefaultControllerFactory
Once you have those you can do something like the following:
MyContainer container; // this needs to be a class level member of the asax
var configuration = GlobalConfiguration.Configuration;
container = new MyContainer() // may need additional stuff here depending on DI tool used
configuration.DependencyResolver = new MyDependancyResolver(container);
var mvcControllerFactory = new MyFactory(container.Kernel);
ControllerBuilder.Current.SetControllerFactory(mvcControllerFactory);
You would call the above code from the asax Application_Start()
See this answer for more specifics on using Ninject and MVC3