WCF RIA Service with Unity 3.5.1.0 - wcf

I'm trying to Use this Blog for WCF RIA Applcation . So I Create a Silverlight Nevigation Applciation which gave me 2 projects abs & abs.Web
More I create 3 project in solution :
abs.Data (c#), DbContext Implemeantion of Repository Interfaces +Factory to provide What user want.
abs.Data.Contarct (c#) Interfaces for Operations Repository
abs.Data.Model (c#) - Contains POCO - EF 6
Now I created A wcf Service in abs.Web project which have constructor injection of a Repository to get my job done in operation contracts.
So I tried using Unity here under the guidence with below blog
http://jamesheppinstall.wordpress.com/2012/06/20/windows-communication-foundation-resolving-wcf-service-dependencies-with-unity/
Now I'm getting
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
**Stack Trace: **
[InvalidOperationException: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.]
System.ServiceModel.Dispatcher.InstanceBehavior..ctor(DispatchRuntime dispatch, ImmutableDispatchRuntime immutableRuntime) +12761206
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime..ctor(DispatchRuntime dispatch) +173
System.ServiceModel.Dispatcher.DispatchRuntime.GetRuntimeCore() +85
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpened() +148
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +321
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +139
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +310
System.ServiceModel.Channels.CommunicationObject.Open() +36
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +91
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +598
[ServiceActivationException: The service '/DomainServices/UserWcfService.svc' cannot be activated due to an exception during compilation. The exception message is: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host..]
System.Runtime.AsyncResult.End(IAsyncResult result) +499812
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +178
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +6
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446
My all classes are same as like Blog.

WCF Ria has its own factory.
Simply put
public class MyDomainServiceFactory : IDomainServiceFactory
{
#region IDomainServiceFactory Members
public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
{
try
{
if (!typeof (DomainService).IsAssignableFrom(domainServiceType))
{
throw new ArgumentException(String.Format("Cannot create an instance of {0} since it does not inherit from DomainService", domainServiceType), "domainServiceType");
}
if (IoC.IsRegistered(domainServiceType))
{
var dmnService = (DomainService) IoC.Resolve(domainServiceType);
dmnService.Initialize(context);
return dmnService;
}
else
{
//if the IoC container doesn't know the service, simply try to call its default constructor
//could throw proper exception as well
var dmnService = (DomainService) Activator.CreateInstance(domainServiceType);
dmnService.Initialize(context);
return dmnService;
}
}
catch (Exception ex)
{
ExceptionHandler.HandleException(ex);
return null;
}
}
public void ReleaseDomainService(DomainService domainService)
{
domainService.Dispose();
}
#endregion
}
and somewhere on your bootstrapping code add
DomainService.Factory = new MyDomainServiceFactory();
of course, the word IoC in the factory identify the unityContainer (is actually a static façade against it)

Related

Cannot create database migration on EF Core but It can when you ask to EnsureCreate database

I am trying to inject some repository to a service and some services to a controller but I am using the DbContext is an assembly that is not the startup project but oddily when i try to call to create a migration it tells me this design is not allowed but if I call the EnsureCreated() method it allows me to create the database... what could be happening
the error
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions1[Repository.AppDbContext.AppDbContext]' while attempting to activate 'Repository.AppDbContext.AppDbContext'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13() --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13() at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl
here is the Service DI
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("ManagementServiceDb"));
});
services.AddIdentity<ApplicationUser, IdentityRole>(options => {
options.SignIn.RequireConfirmedAccount = false;
options.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<AppDbContext>();
services.AddScoped<IRepository<Producto>, ProductoRepositorio>();
services.AddScoped<IRepository<RegistroActividad>, RegistroActividadRepositorio>();
services.AddScoped<IRepository<ProductoRegistroActividad>, RegistroActividadesProductoRepositorio>();
services.AddScoped<IRepository<TipoActividad>, TipoActividadRepositorio>();
services.AddScoped<IRepository<ApplicationUser>, UsuarioRepositorio>();
services.AddScoped<UnidadRepositorio>();
services.AddScoped<ProductosServicios>();
services.AddScoped<UsuarioServicio>();
services.AddScoped<UnidadServicios>();
services.AddControllersWithViews();
}
Try to add a parameterless constructor in your DbContext class.
If that doesn't work you might need to add a design time factory as described here.

microsoft grpc-for-wcf-developers-master code fails on IIS

getting the grpc-for-wcf-developers-master, I tried to host the WCF service in the tradersys on IIS version 10 on Windows 10, which throws an exception:
Error by IIS
The AutofacServiceHost.Container static property must be set before services can be instantiated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The AutofacServiceHost.Container static property must be set before services can be instantiated.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
I'm aware of this issue as discussed several times here, such as this post.
Yet the code by Microsft contains the appropriate autofac container.
the question is:
Is there any special settings on IIS for resolving this issue?
as I said earlier IISExpress just works fine.
seems the AppInitialize() method in which
AutofacHostFactory.Container = builder.Build();
resides, doesn't invoke.
Based on your code, I found that you need to integrate IOC with WCF, which needs to change your code.
Here is my demo:
This is my project directory.We need to add two classes: ManualProxy and CustomServiceHostFactory.
public class CustomServiceHostFactory : ServiceHostFactory
{
protected override System.ServiceModel.ServiceHost
CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
ManualProxy.TargetFactory = () => new PortfolioService(new PortfolioRepository());
return base.CreateServiceHost(typeof(ManualProxy), baseAddresses);
}
}
This is the CustomServiceHostFactory class.
public class ManualProxy : IPortfolioService
{
private readonly IPortfolioService _target;
public static Func<object> TargetFactory;
public ManualProxy()
{
_target = (IPortfolioService)TargetFactory();
}
public Task<Portfolio> Get(Guid traderId, int portfolioId)
{
return _target.Get(traderId,portfolioId);
}
public Task<List<Portfolio>> GetAll(Guid traderId)
{
return _target.GetAll(traderId);
}
}
This is the ManualProxy class.
The SVC file needs to be changed as above picture.

Visual Studio Express 2012 - Silverlight-Enabled WCF Service?

I just started a new Silverlight project with Visual Studio Express 2012 for Web.
I created a Silverlight-enabled WCF service to access a SQL Server database, with EF 5.
The problem I'm having is that the service doesn't seem to be able to return any entity retrieved from the database. A new entity or any old object is returned just fine, but when I try to return an entity from the context I get the following exception:
{System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.<EndGetResponse>b__9(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
--- End of inner exception stack trace ---
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.DataServiceClientChannel.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.NewProj.DataSvcRef.DataService.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.OnEndGetAgency(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)}
The service method code couldn't be simpler:
[OperationContract]
public Contact GetContact(int aID)
{
Contact res = null;
using (var db = new OFBEntities())
{
try
{
res = db.Contacts.Find(aID);
}
catch (Exception ex)
{
res = null;
}
return res;
}
}
As I mentioned, if I return a newly created object (return new Contact(){ name="test contact};), or return a type that is not in context (say an integer for example), everything works fine.
Is this a limitation of the express version, or am I forgetting some settings? In the past I have created some Silverlight apps that consumed data services with VS 2010, Silverlight 4, and I don't remember having to set anything special, but maybe I just forgot that I did?
Any help is appreciated!
EDIT:
Could it have anything to do with DbContext and the way it is serialized? I've never used DbContext before, I always used the default ObjectContext in EF 4...
EDIT2: SOLUTION
It's been a while, but I had other things to work :o)
In case anybody is in the same boat, the problem was in the serialization by the service. DbContext by default creates proxies, which don't agree with serialization. I am not sure why yet - indeed, I need to educate myself about those proxies - but disabling them solves my serialization issue.
Thanks for the comment Pawel, I mistakenly thought my serialization was going OK, rechecking the server-side error put me back on the right track.
The problem was with automatic proxy creation by the DBContext, which interfered with the serialization.
Proxies are on by default in DBContext, you can disable them in the class constructor
this.Configuration.ProxyCreationEnabled = false;
or after creating an instance of your DBContext
using (var db = new myDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
...
}
Not sure why yet, but it works. Time to go read up on that!

Injecting dependencies into MVC3 WCF services using Ninject extensions

I have an MVC3 application which should expose some functions via WCF. Some of these functions have dependencies and I'd like to inject them using Ninject, but I must be missing something obvious here as this does not work. Could anyone give a hint? Here's what I did:
1) in my MVC3 app, I add Ninject Wcf extensions via nuget.
2) I add a .svc file like:
<%# ServiceHost Service="MyWeb.LookupService"
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory"%>
3) I add the corresponding code like (that's just a test so I'm using a dummy interface right here):
[ServiceContract]
public interface ILookupService
{
[OperationContract]
int GetProjectIdByCode(string sCode);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class LookupService : ILookupService
{
private readonly ISomeRepository _repository;
public LookupService(ISomeRepository repository)
{
_repository = repository;
}
public int GetProjectIdByCode(string sCode)
{
//... use _repository
}
}
4) in App_Start/NinjectMVC3.cs:
private static void RegisterServices(IKernel kernel)
{
string sConnection = ConfigurationManager.ConnectionStrings["SomeEntities"].ConnectionString;
// WCF
kernel.Bind<ServiceHost>().To<NinjectServiceHost>();
kernel.Bind<ISomeRepository>()
.To<AConcreteRepository>()
.WithConstructorArgument("sConnection", sConnection);
}
Now, when I access the svc I get the following exception from Ninject:
System.ArgumentNullException was unhandled by user code
Message=Cannot be null Parameter name: root Source=Ninject
ParamName=root StackTrace:
at Ninject.Infrastructure.Ensure.ArgumentNotNull(Object argument, String name) in
c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Infrastructure\Ensure.cs:line
20
at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot
root, Type service, Func2 constraint, IEnumerable1 parameters,
Boolean isOptional, Boolean isUnique) in
c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line
258
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in
c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line
37
at Ninject.Extensions.Wcf.NinjectServiceHostFactory.CreateServiceHost(Type
serviceType, Uri[] baseAddresses) in
c:\Projects\Ninject\Maintenance2.2\ninject.extensions.wcf\src\Ninject.Extensions.Wcf\NinjectServiceHostFactory.cs:line
48
at System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String
normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String
normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath)
Can you try to add a protected parameterless constructor to your implementation class.
Guess the servicehost needs a parameterless constructor as well.
I had a look at the Ninject service host factory and from the stack trace provided by you. It looks its failing whne making the following checks:
Ensure.ArgumentNotNull((object) root, "root");
Ensure.ArgumentNotNull((object) service, "service");
Ensure.ArgumentNotNull((object) parameters, "parameters");
Make sure that you are passing all the required parameters when using the NinjectServiceHostFactory. Worth trying to change the order of registration.
Also go through the following link here that explains how to use Ninject to host a wcf service.

Wcf Data Service Service operations

Getting error when I run the wcf data service with the code following the error message:
"The server encountered an error processing the request. See server logs for more details."
Code:
public class WcfDataService1 : DataService<Entities1>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("GetData", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
[WebGet()]
public IQueryable GetData(int Id)
{
if (assayId > 0)
{
var query = from a in this.CurrentDataSource.Entity
where a.ID == Id
select a;
return query;
}
else
throw new DataServiceException(400, "ID is not valid");
}
}
The same code works when I dont return anything from the operation.
UPDATE: The server logs say:
"WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/44530215
Exception: System.ServiceModel.ServiceActivationException: The service '/MyWcfDataService.svc' cannot be activated due to an exception during compilation. The exception message is: The type 'MyWcfDataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.. ---> System.InvalidOperationException: The type 'MyWcfDataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.
at System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
Process Name: WebDev.WebServer40
Process ID: 1124
For more information, see Help and Support Center at
Can anyone please help me with the solution.
Also, if I want to expose my own entity and not the one created by EF, how to go about doing that.. any ideas??
Just modified the return type to
IQueryable<Entity> and it worked.