Error while creating remote listener in service fabric stateful service (.NET Core application) - service-fabric-stateful

Error: Does not contain a definition for 'CreateServiceRemotingListener' and no extension method 'CreateServiceRemotingListener' accepting a first argument of type could be found (are you missing a using directive or an assembly reference?)
Below are the steps which I followed,
Created an interface that implements IService.
`
using Microsoft.ServiceFabric.Services.Remoting;
using System.Threading.Tasks;
public interface IFileService: IService
{
Task<string> GetStringByName(string name);
}
`
Included following packages in stateful service named as FileService.
`
using System. Fabric;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
`
Implemented IFileService interface in FileService.
`
internal sealed class FileService : StatefulService, IFileService
{
public FileService(StatefulServiceContext context)
: base(context)
{ }
public FileService(StatefulServiceContext context, IReliableStateManagerReplica stateManagerReplica) : base(context, stateManagerReplica)
{
}
public Task<string> GetStringByName(string name)
{
return Task.FromResult<string>(name);
}
/// <summary>
/// Optional override to create listeners (e.g., HTTP, Service Remoting, WCF, etc.) for this service replica to handle client or user requests.
/// </summary>
/// <remarks>
/// For more information on service communication, see https://aka.ms/servicefabricservicecommunication
/// </remarks>
/// <returns>A collection of listeners.</returns>
protected override IEnumerable<ServiceReplicaListener>
CreateServiceReplicaListeners()
{
return new[] { new ServiceReplicaListener(this.CreateServiceRemotingListener) };
}}
`

The ServiceRemotingExtensions class is located in Microsoft.ServiceFabric.Services.Remoting.Runtime namespace (that isn't included).
The important point to mention is that CreateServiceRemotingListener is deprecated. The recommended method to use is CreateServiceRemotingReplicaListeners.
Hope this helps.
UPDATE 2019/01/28
Here is the sample code:
using System.Collections.Generic;
using System.Fabric;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Remoting;
using Microsoft.ServiceFabric.Services.Remoting.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
namespace JustService
{
public interface IRemotingService : IService
{
// Remoting methods
}
internal sealed class JustService : StatefulService, IRemotingService
{
public JustService(
StatefulServiceContext context)
: base(context)
{
}
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
return this.CreateServiceRemotingReplicaListeners();
}
}
}
Please note that in order to use CreateServiceRemotingReplicaListeners extension method the service should implement an interface derived from IService.

Related

An error occurred while accessing the Microsoft.Extensions.Hosting services. After Adding ASP.NET identity

I have DataContext and StartUp class in different projects and to add a new migration in Data project I used the below command:
dotnet ef migrations add IdentityAdded -s ..\API\API.csproj
And here is project structure:
I just added ASP.Net Core Identity to the project based on .Net 5 and configured it as below:
public class DataContext : IdentityDbContext<AppUser, AppRole, int,
IdentityUserClaim<int>, AppUserRole, IdentityUserLogin<int>,
IdentityRoleClaim<int>, IdentityUserToken<int>>
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
ChangeTracker.LazyLoadingEnabled = false;
}
... DbSets
... protected override void OnModelCreating(ModelBuilder modelBuilder)
{ ... }
}
IdentityServiceExtension.cs:
public static class IdentityServiceExtension
{
public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddIdentityCore<AppUser>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddRoles<AppRole>()
.AddRoleManager<RoleManager<AppRole>>()
.AddSignInManager<SignInManager<AppUser>>()
.AddRoleValidator<RoleValidator<AppUser>>()
.AddEntityFrameworkStores<DataContext>();
}
}
I just inherited some classes such as AppUser, AppRole and AppUserRole from Identity Classes like this:
public class AppRole : IdentityRole<int>
{
public ICollection<AppUserRole> TheUserRolesList { get; set; }
}
After running the migration I get the following error:
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.RoleManager1[Core.Models.Entities.User.AppRole] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.RoleManager1[Core.Models.Entities.User.AppRole]': Implementation type 'Microsoft.AspNetCore.Identity.RoleValidator1[Core.Models.Entities.User.AppUser]' can't be converted to service type 'Microsoft.AspNetCore.Identity.IRoleValidator1[Core.Models.Entities.User.AppRole]')
What's wrong with this implementation?
You didn't register properly, instead of:
.AddRoleValidator<RoleValidator<AppUser>>()
add:
.AddRoleValidator<RoleValidator<AppRole>>()
Your error points out that it can't instantiate Microsoft.AspNetCore.Identity.RoleValidator with the Core.Models.Entities.User.AppUser, instead it requires Core.Models.Entities.User.AppRole.

Service fabric Statefulservice throwing error at CreateServiceRemotingListener

I am getting the below error. I have added required nuget package Microsoft.ServiceFabric.Services.Remoting v3.0.472.
'VotingDataService' does not contain a definition for
'CreateServiceRemotingListener' and no extension method
'CreateServiceRemotingListener' accepting a first argument of type
'VotingDataService' could be found (are you missing a using directive
or an assembly reference?)
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Remoting;
using Microsoft.ServiceFabric.Services.Remoting.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using System;
using System.Collections.Generic;
using System.Fabric;
using System.Threading.Tasks;
namespace VotingDataService
{
public interface IVotingDataService2 : IService
{
Task<int> AddVote(string voteItem);
}
/// <summary>
/// The FabricRuntime creates an instance of this class for each service type instance.
/// </summary>
internal sealed class VotingDataService : StatefulService, IVotingDataService2
{
public VotingDataService(StatefulServiceContext context)
: base(context)
{ }
public Task<int> AddVote(string voteItem)
{
throw new NotImplementedException();
}
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
return new[]
{
new ServiceReplicaListener(context =>
this.CreateServiceRemotingListener(context))
};
}
}
}
Don't forget to implement an interface that extends IService. The extension method works on IService.
(IMyService in the example)
More info here.

IoC avoid to inject container

I am working with IoC and more precisely with windsor and I have an amletic doubt about one thing.
Right now I am implementing the DDD Command layer so for each command I have a concrete class as following
public class CreateUserCommand : IDomainCommand{
/// implementation
}
Each command has 1 or more handlers with the following implementation
public class CreateUserHandler : IDomainCommandHandler<CreateUserCommand>
{
public void Handle(CreateUserCommand command)
{
/// implementation
}
}
The problem arise with my Command Dispatcher. I am using the following form at the moment
public class CommandDispatcher : ICommandDispatcher
{
private IWindsorContainer container;
public CommandDispatcher(IWindsorContainer container)
{
this.container = container;
}
public void Dispatch<T>(T command)
{
var commandHandler = container.Resolve<ICommandHandler<T>>();
commandHandler.Handle(command);
}
}
What I don't like is the awareness of the dispatcher about the IoC container but in the same way I don't know how I can sort of resolve the handlers only when I need them.
Shell I inject an handler factory inside the Dispatcher and use it to resolve my handlers at runtime?
I'd use the typed factory facility to create a factory to replace the container usage. Conceptually the idea is the same, but it removes the dependency on the container.
The factory (no implementation, the facility takes care of that):
public interface ICommandHandlerFactory
{
ICommandHandler<T> Create<T>();
}
Registration:
// requires Castle.Facilities.TypedFactory namespace
windsorContainer.AddFacility<TypedFactoryFacility>();
// AsFactory() is an extension method in the same namespace
windsorContainer.Register(Component.For<ICommandHandlerFactory>().AsFactory());
Then in your class:
public class CommandDispatcher : ICommandDispatcher
{
private ICommandHandlerFactory commandHandlerFactory;
public CommandDispatcher(ICommandHandlerFactory commandHandlerFactory)
{
this.commandHandlerFactory = commandHandlerFactory;
}
public void Dispatch<T>(T command)
{
var commandHandler = commandHandlerFactory.Create<T>();
commandHandler.Handle(command);
}
}
It's okay for infrastructure code that is part of your composition root to take a dependency on the container. This is not an implementation of the Service Locator anti-pattern, since the Service Locator is about role and not mechanics.
In other words, as long as your CommandDispatcher is part of the composition root (and contains just infrastructure, no business logic) it is okay to let it depend on the container.

Will my Unit of Work implementation cause memory leak?

I implemented my repository pattern and unit of work in the following way:
How to create a simple data access layer
How to create unit of work
and I was asked if create multiple instance of my database (which is the unit of work) will cause memory leak? and what are the downside of such implementation? or is the implementation done right?
Thanks.
What you should worry about is the creation of the DbContext as this is expensive.
I typically use one DbContext per request instead of creating multiple DbContext instances everywhere.
I store it in the HttpContext object and dispose of it at the end of the request.
You can find more info on it here
Find below my modified implementation. (original was from the link above and used ObjectContext).
My context class
using System.Data.Entity;
using System.Data.Objects;
using System.Web;
using Fot.Admin.Models;
namespace Context
{
public static class ContextManager
{
internal const string DB = "MY_DB_CONTEXT";
/// <summary>
/// Get an instance that lives for the life time of the request per user and automatically disposes.
/// </summary>
/// <returns>Model</returns>
public static T AsSingleton<T>() where T : DbContext, new()
{
HttpContext.Current.Items[DB] = (T)HttpContext.Current.Items[DB] ?? new T();
return (T)HttpContext.Current.Items[DB];
}
}
}
My Context Module
using System;
using System.Data.Entity;
using System.Data.Objects;
using System.Web;
namespace Context
{
/// <summary>
/// Entity Module used to control an Entities DB Context over the lifetime of a request per user.
/// </summary>
public class ContextModule : IHttpModule
{
private const string DB = ContextManager.DB;
void context_EndRequest(object sender, EventArgs e)
{
Dispose();
}
#region IHttpModule Members
public void Dispose()
{
if(HttpContext.Current != null)
{
if (HttpContext.Current.Items[DB] != null)
{
var entitiesContext = (DbContext) HttpContext.Current.Items[DB];
entitiesContext.Dispose();
HttpContext.Current.Items.Remove(DB);
}
}
}
public void Init(HttpApplication context)
{
context.EndRequest += new EventHandler(context_EndRequest);
}
#endregion
}
}
In my web.config under <httpModules> i add this below.
<add name="ContextModule" type="Context.ContextModule" />
This ensures that the end_Request is called after every request so you can dispose the context properly.
When you need the DbContext usage is as below.
var Context = ContextManager.AsSingleton<MyDBContext>();

Add methods to generated WCF client proxy code

I'd like to add one additional method for each service operation in my WCF client proxy code (i.e. the generated class that derives from ClientBase). I have written a Visual Studio extension that has an IOperationContractGenerationExtension implementation, but this interface only seems to expose the ability to modify the service interface, not the ClientBase-derived class.
Is there any way to generate new methods in the proxy client class?
As far as I know, those classes are always partial classes:
public partial class MyWCFServiceClient : ClientBase<IMyWCFService>, IMyWCFService
{
...
}
so you can easily extend them with your own, second file that adds method to the same partial class:
YourOwnFile.cs
public partial class MyWCFServiceClient
{
public void NewMethod1()
{
}
public void NewMethod2()
{
}
}
I got around this by generating a wrapper class for the ClientBase-derived class during the import process. I actually first tried generating an additional partial class with the same name as the client class, but that caused the rest of the code generation to stop working properly.
So my final generated code looks something like:
(generated by the built-in WCF proxy generator):
public interface ServiceReference1
{
IAsyncResult BeginWebMethod1(AsyncCallback callback, object asyncState);
void EndWebMethod1(IAsyncResult result);
IAsyncResult BeginWebMethod2(AsyncCallback callback, object asyncState);
void EndWebMethod2(IAsyncResult result);
// ...
}
public class ServiceReference1Client
{
public event EventHandler<AsyncCompletedEventArgs> WebMethod1Completed;
public event EventHandler<AsyncCompletedEventArgs> WebMethod2Completed;
public void WebMethod1Async() { /* ... */ }
public void WebMethod2Async() { /* ... */ }
// ...
}
(generated by my custom IOperationContractGenerationExtension):
public class ServiceReference1Wrapper
{
private ServiceReference1Client _client;
public ServiceReference1Wrapper(ServiceReference1Client client)
{
_client = client;
}
public IObservable<AsyncCompletedEventArgs> WebMethod1()
{
_client.WebMethod1Async();
// ...
}
public IObservable<AsyncCompletedEventArgs> WebMethod2()
{
_client.WebMethod2Async();
// ...
}
// ...
}
Note: I'm using Silverlight, so that's why everything is async.