How to use Automoqer with autofac - c#

I'm trying to resolve a concrete class having a container with autofac
My setup is something like this
[TestInitialize]
public void Setup()
{
_automoqer = new AutoMoqer();
_distributeProcessSink = _automoqer.Resolve<DistributedSaveHistorySink>();
}
and my concrete class looks like this
private readonly Func<string, IConsolidationContext, IConsolidationStore> _consolidationStoreFactory;
public DistributedSaveHistorySink(Func<string, IConsolidationContext, IConsolidationStore> consolidationStoreFactory)
{
_consolidationStoreFactory = consolidationStoreFactory;
}
Initialization method xx threw exception.
Microsoft.Practices.Unity.ResolutionFailedException:
Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency
failed, type = "xx.DistributedSaveHistorySink", name = "(none)".
Exception occurred while: while resolving.
Exception is: TargetInvocationException - Exception has been thrown by the target
of an invocation.
also my container configuration looks like this
builder.RegisterType<DistributedSaveHistorySink>()
.Keyed<IProcessSink<MergeMessage>>(PipelineType.Default)
.PropertiesAutowired();

Related

NLog how to use Isolated LogFactories with a custom logger class

I ran into a issue because LogManager is global, so my two projects were overriding each other's logging config. NLog log calls in the first project would work fine, but then when calling into the second project, all future log calls would be logged with the second projects config.
Example:
Target 1 "First log in first project" (supposed to be target 1)
Target 2 "Second log in second project" (supposed to be target 2)
Target 2 "Third log in first project" (supposed to be target 1)
I found Isolated logfactory which solved my issue, now the loggers has the correct config. However I cannot figure out how to use my custom NLog class with this method of making LogFactories.
This works great (but doesn't let me use my custom class with methods):
private static Logger logger = MyLogger.MyLogManager.Instance.GetCurrentClassLogger();
This:
private static MyLogger logger = (MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger();
Throws:
System.TypeInitializationException: 'The type initializer for 'MyProject.MyClass.MyMethod' threw an exception.'
InvalidCastException: Unable to cast object of type 'NLog.Logger' to type 'MyProject.NLogConfigFolder.MyLogger'.
I have tried to cast Logger to MyLogger but have not been able to do so successfully.
Here is my setup for the isolated LogFactory:
public class MyLogger : Logger
{
public class MyLogManager
{
public static LogFactory Instance { get { return _instance.Value; } }
private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);
private static LogFactory BuildLogFactory()
{
string configFilePath = "path/to/my/config"
LogFactory logFactory = new LogFactory();
logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory);
return logFactory;
}
}
// Other methods here
}
Thank you for your time and help with this problem.
Think you just need to change:
(MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger()
Into this:
MyLogger.MyLogManager.Instance.GetCurrentClassLogger<MyLogger>()
See also: https://nlog-project.org/documentation/v5.0.0/html/Overload_NLog_LogFactory_GetCurrentClassLogger.htm

Method overloading in Unity container

I am registering my interface in App.config. But while resolving, I am getting the below exception.
Microsoft.Practices.Unity.ResolutionFailedException
HResult=0x80131500
Message=Resolution of the dependency failed, type = "Philips.DI.Interfaces.UW.DtoModel.IModelProvider`1[Philips.DI.UW.PatientOrchestrator.Interfaces.PatientScheduleDataModel]", name = "LoginPage".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Philips.DI.Interfaces.UW.DtoModel.IModelProvider`1[Philips.DI.UW.PatientOrchestrator.Interfaces.PatientScheduleDataModel], is an interface and cannot be constructed. Are you missing a type mapping?
At the time of the exception, the container was:
Resolving Philips.DI.Interfaces.UW.DtoModel.IModelProvider`1[Philips.DI.UW.PatientOrchestrator.Interfaces.PatientScheduleDataModel],LoginPage
var proxy = container.Resolve<T>("LoginPage", new ResolverOverride[] {
new ParameterOverride("unityContainer", container),new ParameterOverride("serviceEndPoint", serviceEndPoint)});
public SyncProxy(IUnityContainer unityContainer, ServiceEndPoint serviceEndPoint) : base(unityContainer, serviceEndPoint)
{
_clientDataSyncWrapper = unityContainer.Resolve<ClientDataSyncWrapper>();
RegisterPushMessages();
}
[InjectionConstructor]
public SyncProxy(IUnityContainer unityContainer, string endPoint) : base(unityContainer, endPoint)
{
_clientDataSyncWrapper = unityContainer.Resolve<ClientDataSyncWrapper>();
RegisterPushMessages();
}

How to intercept a factory in lightinject

Not sure what to do here. invocationInfo.Proceed() always fails when trying to Intercept a factory that has constructor injection.
var container = new ServiceContainer();
container.Register<ICool,Cool>();
container.Register<ILogger, Logger>();
container.Register<IInterceptor, LoggingInterceptor>();
//Two problem lines
container.Register<int, IAwesome>((factory, value) => new Awesome(value, factory.GetInstance<ICool>()));
container.Intercept(sr => sr.ServiceType == typeof(IAwesome), sf => sf.GetInstance<IInterceptor>());
var awesome = container.GetInstance<int,IAwesome>(100);
awesome.Yo();
fails at this method in my interceptor.
public class LoggingInterceptor : IInterceptor
{
private ILogger _logger;
public LoggingInterceptor(ILogger logger)
{
_logger = logger;
}
public object Invoke(IInvocationInfo invocationInfo)
{
var returnValue = invocationInfo.Proceed(); //Exception here
return returnValue;
}
}
Exception:
An exception of type 'System.InvalidCastException' occurred in LightInject.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Func`1[ConsoleApplication1.IAwesome]' to type 'System.Object[]'.
Sorry I couldn't make a new tag for Lightinject. Not enough rep :/
I am the author of LightInject and it has been confirmed to be a bug when intercepting service instances that relies on runtime arguments such as the Awesome class.
The bug has been fixed and I will post back here as soon as a new NuGet package is available.
Best regards
Bernhard Richter

ServiceStack - Error trying to resolve Service {X} or one of its autowired dependencies

I am using servicestack and having problems with auto wiring.
Error trying to resolve Service '{Service}' or one of its autowired dependencies (see inner exception for details)
I don't need help figuring how exactly what the problem is. What I actually want is a way to see the inner exception. The inner exception should tell me the except problem without me having to figure it out but it not displayed in either the exception returned, or in the logs.
Setting DebugMode doesn't help either, it just includes the stack track of the topmost exception.
So basically, how do I stop servicestack from hiding the inner exception details?
I ran into this same issue and it ended up being that there was an exception being thrown inside of the constructor that I had created for the particular endpoint class. Example...
public class PartnerService : Service
{
private PartnerManagementService _partnerManagementService;
public PartnerService()
{
var configuration = new Configuration();
_partnerManagementService = new PartnerManagementService(configuration);
}
public object Get(PartnerGet partner)
{
try
{
var partners = _partnerManagementService.getPartners();
if (!partners.Any())
{
return new HttpError(HttpStatusCode.NotFound, "Partners Could not be found");
}
return partners;
}
catch (Exception e)
{
return new HttpError(HttpStatusCode.InternalServerError, e);
}
}
If it so happens that an exception is thrown inside of the constructor, ServiceStack will not be able to resolve the service or one of its dependencies, in this case that dependency being the constructor for the class.
If you put a try/catch in the constructor for the class you could get an exception that actually makes sense.
ServiceStack should already return the inner Exception, i.e. here's the source of the error:
private Exception CreateResolveException<TService>(Exception ex)
{
var errMsg = "Error trying to resolve Service '{0}' or one of its autowired dependencies (see inner exception for details).".Fmt(typeof(TService).FullName);
return new Exception(errMsg, ex);
}
Basically there was a problem with your IOC configuration and that one of the dependencies caused an error.
You can change ServiceStack to serialize the Inner Exception with:
SetConfig(new EndpointHostConfig {
ReturnsInnerException = true,
});
But this already defaults to true.
So the exception should already contain the Inner Exception, are you referring to what Exception gets serialized or the exception thrown in code?
One option could be to grab the actual source code from Github and add it as a project to your solution, as opposed to using a compiled DLL, then you could step through the actual code and see exactly where the exception is raised and why.
I have exactly the same exception.
In my case, it happens once migrated to ServiceStack v4. With v3, all works perfectly.
IoC configuration
public class AppHost : AppHostBase
{
public AppHost() : base("Northwind web services", typeof(CustomersService).Assembly)
{ }
public override void Configure( Container container )
{
SetConfig(new HostConfig
{
DebugMode = true,
ReturnsInnerException = true,
});
var dbFactory = new OrmLiteConnectionFactory("~/Northwind.sqlite".MapHostAbsolutePath(), SqliteDialect.Provider);
container.Register(dbFactory);
// Dependencies
container.RegisterAs<CustomerEntityRepository, ICustomerEntityRepository>();
container.RegisterAutoWired<CustomersService>();
}
}
Base class
public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : IEntity, new()
{
protected IDbConnectionFactory dbFactory { get; set; }
public Repository( IDbConnectionFactory factory )
{
dbFactory = factory;
}
}
Inherited class
public class CustomerEntityRepository : Repository<CustomerEntity>, ICustomerEntityRepository
{
public CustomerEntityRepository( IDbConnectionFactory dbFactory )
: base(dbFactory)
{
}
}
}
Only solution I've found is:
container.RegisterAs<ICustomerEntityRepository>(c => new CustomerEntityRepository(dbFactury));
Here's full exception message returned http://pastebin.com/jJntNN5p

StructureMap error when use with MVC in constructor

When I install StructureMap for my project and use:
public class IndexController : Controller
{
private readonly IMapper<UserModel, UserDto> _mapper;
public IndexController(IMapper<UserModel, UserDto> mapper)
{
_mapper = mapper;
}
public ActionResult Index()
{
List<UserDto> userDb = UserDb.GetAll();
UserModel userModel = _mapper.Map(userDb[0]);
return View();
}
}
After run with an server error message:
No parameterless constructor defined for this object. 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.MissingMethodException: No parameterless constructor defined for this object.
...
But I don't know much about the principle of dependency inversion. Please help me to resolve this.
This is ObjectFactory :
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
// x.For<IExample>().Use<Example>();
});
return ObjectFactory.Container;
}
}
What do I need to do next?
You need to tell StructureMap how to wire up all types that don't follow the default convention (which you use in your scan). The default convention is to wire up all interfaces to concrete implementations with the same name as the interface (minus the "I" prefix).
In your case you need to tell StructureMap to wire up all needed closed generic types of IMapper using:
x.For(typeof(IMapper<,>)).Use(typeof(MyConcreteMapper<,>);
Put the line above where you currently have the x.For<IExample>().Use<Example().

Categories