Autofac doesnot cannot resolve types when in IIS sub application - autofac

Does any one know why autofac fails to initialize the mvc controllers when there is an applicaton in the root and also another in sub application in IIS? How to fix this?
When the apps are hosted in different Websites in IIS they work without a problem.
so in the image, the root app(mvc web) deployed in the root works but not the webservice (mvc api).
error is
An error has occurred.An error occurred when trying to create a controller of type 'UserController'. Make sure that the controller has a parameterless public constructor.System.InvalidOperationException at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()An error has occurred.An exception was thrown while invoking the constructor 'Void .ctor()' on type 'BurpDaddyEntities'. ---> The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. (See inner exception for details.)Autofac.Core.DependencyResolutionException at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)

While the top-level exception appears to be from Autofac, if you look down at the inner exception issue that caused the whole thing, you'll see the true exception is The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. Which means the static constructor for that class went awry.
Fortunately, there's actually a question (with an answer!) directly about exactly what you're facing here with nested websites using Entity Framework:
The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception on a Sub Website

Related

Autofac An error occurred during the activation of a particular registration

I have inherited a .NET project which keeps throwing Autofac errors but I'm not sure what this error message is telling me. Any help would be appreciated?
An error occurred during the activation of a particular registration. See the inner exception for details.
Registration:
Activator = ImplementationResourceRepository (ReflectionActivator),
Services = [Interfaces.IImplementationResourceRepository],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = None,
Ownership = OwnedByLifetimeScope ---> None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'CCES.Repositories.ImplementationResourceRepository' can be invoked with the available services and parameters:
Cannot resolve parameter 'Interfaces.IRepository repository' of constructor 'Void .ctor(Interfaces.IRepository)'. (See inner exception for details.)
Type ImplementationResourceRepository has a constructor that takes an instance that implements Interfaces.IRepository in it's constructor but no types were registered as Interfaces.IRepository. You need to register a type that implementats Interfaces.IRepository as that interface with Autofac.
Something similar to this:
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<Implementations.Repository>()
.As<Interfaces.IRepository>()
.InstancePerDependency();
}

Sharprepository Autofac InstancePerApiRequest in Webapi environment not working

Does anyone have a working example of sharprepository intergration with autofac using InstancePerApiRequest for DbContext?
I am registering my dbcontext thusly:
builder.RegisterType<AuditTestEntities>().As<DbContext>().InstancePerApiRequest();
If I remove the InstancePerApiRequest, sharprepository is able to get a dbcontext. But with the InstancePerApiRequest, I get the error message pasted below. Basically the crux of the error is, I suspect, the way sharprepository makes the call:
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
The full error stack:
iisexpress.exe Error: 0 : Operation=DefaultHttpControllerActivator.Create, Exception=System.InvalidOperationException: An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor. ---> Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor()' on type 'AccountRepository'. ---> Could not resolve type 'System.Data.Entity.DbContext' using the 'AutofacDependencyResolver'. Make sure you have configured your Ioc container for this type. View the InnerException for more details. (See inner exception for details.) ---> SharpRepository.Repository.Ioc.RepositoryDependencyResolverException: Could not resolve type 'System.Data.Entity.DbContext' using the 'AutofacDependencyResolver'. Make sure you have configured your Ioc container for this type. View the InnerException for more details. ---> Autofac.Core.DependencyResolutionException: No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
Okay found the issue. There is a problem with using the SharpRepository AutofacDependencyResolver when using the MVC or Web API integration and trying to use the scope InstancePerApiRequest or InstancePerHttpRequest. Autofac expects those items to be resolved from the System.Web.DependencyResolver.Current instead of from the Autofac IContainer directly as the AutofacDependencyResolver is currently doing.
Here is how you can fix the issue right now until we make an overload for AutofacDependencyResolver that fixes the issue.
You will need to create your own dependency resolver within your project like this one:
public class CustomAutofacDependencyResolver : BaseRepositoryDependencyResolver
{
private readonly IDependencyResolver _resolver;
public CustomAutofacDependencyResolver(IDependencyResolver resolver)
{
_resolver = resolver;
}
protected override T ResolveInstance<T>()
{
return _resolver.GetService<T>();
}
protected override object ResolveInstance(Type type)
{
return _resolver.GetService(type);
}
}
And then register it with SharpRepository so it will use it to resolve the DbContext and then it will work as expected.
RepositoryDependencyResolver.SetDependencyResolver(new CustomAutofacDependencyResolver(DependencyResolver.Current));
** Update**
I was testing with MVC and able to replicate the error and fix it but that doesn't work with Web API. I am used to using StructureMap where it works fine using the GlobalConfiguration.Configuration.DependencyResolver.
It seems the issue is that Autofac needs a IDependencyScope that you can access from the HttpRequestMessage but I'm not seeing a way to get to that outside of the ApiController. This describes the issue and the reason: https://groups.google.com/forum/#!msg/autofac/b3HCmNE_S2M/oMmwFE5uD80J
Unfortunately right now I'm at a bit of a loss on the best way to handle this. But I'll keep thinking about it.
So, I was able to get mine working by changing the lifetime scope to InstancePerLifetimeScope. I don't know whether this has any unforeseen consequences or not. Everything appears to be working fine for me so far.

Best way to handle constraint violations when using EJB 3.0 and CMP

I have a web service (built using jaxb/jaxws) that invokes a stateless EJB to store some data in the database. The data is being stored as an entity bean. The entity bean has a unique constraint applied to it via the #Column(unique = true) annotation.
When the web service attempts to save data, the transaction fails, and rightfully so. The problem is that since I am using CMP, the transaction is not committed until after the call to the stateless EJB. The end result is that I am not able to trap the exception and it is getting funneled up to the WS stack and results in an ambiguous fault containing the string: Error committing transaction:;nested exception is: weblogic.transaction.internal.AppSetRollbackOnlyException.
Is there a way to catch the exception being thrown so I can provide more information to the caller? Thank you.
Version information:
Application Server: Oracle Weblogic 10.3
Persistence Provider: Hibernate 3.2.5.ga (JPA 1.0)
JDK/JRE: 1.6_0_05 (provided by Weblogic install)
Update:
I tried to implement an EJB 3 interceptor around the method invocation and this does not appear to work.
public class TestInterceptor {
#AroundInvoke
public Object logCall(InvocationContext context) throws Exception {
System.out.println("Invoking method: " + context.getMethod().getName());
try {
return context.proceed();
} catch (Throwable t) {
System.out.println("I caught an exception: " + t.getMessage());
throw new Exception(t);
}
}
The reason I think this doesn't work is because the processing chain is such that the actual persist happens outside of the method (of course).
You could try using Bean Validation. It's nicely connected with the JPA (invoked during pre-persist, pre-update and pre-remove phases and can be used in different layers of your application.
Unfortunately, as far as I know, if a validation constraint violation occurs, the transaction is marked for rollback... I don't know how you could cope with that but one (seems nasty and untested) way I could think of is to inject a ValidatorFactory and validate the object by yourself. Perhaps then you could catch the ValidationException.
EDIT: I'm not sure if the Bean Validation was available in Java EE 5.
EDIT 2: You can create an interceptor which will catch the exception thrown by the JPA (or more precisely by the database). As the interceptor is invoked as a part of the same transaction as the EJB method you might need to explicitly invoke EntityManager#flush(-) to synchronise changes with the database.

GWT RequestContext ENum in the request

If we use enum as one of the attribute in the Request invocation , it throws an UnsupportedOpeationException and does not even invoke the service method on the server.
#Service(value = DesignService.class, locator = DesignServiceLocator.class)
public interface DesignRequest extends RequestContext {
Request<List<DesignProxy>> findDesign(SortEnum sortorder);
}
when we invoke the designRequest.findDesign(sortorderEnum).fire() the UnsupportOperationException is thrown on the javascript console on chrome dev tools/Firebug console.
Looks like it is related to Issue 6504, which will throw an UnsupportedOperationException if it fails to find the type you are using - consider trying to change to class methods in your enum, or wait until 2.4 is released.
If you are not using anonymous enum instances, can you post more info about this error, such as where the exception is thrown from?

ArgumentException when creating instance of object that inherits from ObjectContext

I'm loosely following an excellent series of blog posts by Kazi Manzur Rashid as a learning exercise for learning how to implement some new (for me at least) design patterns, but I'm getting trouble from the start.
I've basically copied his code for the Database, RepositoryBase and RepositoryBaseTests classes, but when I try to run the tests, I get an error message saying
Unable to create instance of class Booking.Infrastructure.EntityFramework.Repositories.Tests.RepositoryBaseTests. Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0..
Through the debugger I have verified that the exception is thrown on the constructor for the Database class, which looks like this:
public Database(
IConfigurationManager configurationManager,
string connectionstringName)
: base(
GetConnectionString(configurationManager, connectionstringName),
"BookingEntities")
{ // Nothing happens here }
The error is thrown when calling the base constructor, and if I'd hard-code the values that I'm currently sending in, it would look like this:
: base("Dummy connStr", "BookingEntities")
Why doesn't this work?
"Dummy connStr" is not a valid EF connection string.
A valid EF connection string looks like:
connectionString="metadata=res://*/Data.Model.csdl|res://*/Data.Model.ssdl|res://*/Data.Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SERVERNAME\SQLDEV2008;Initial Catalog=DBName;Integrated Security=True;MultipleActiveResultSets=True""