w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Getting a singleton instance using SimpleInjector for a class which implements a generic type, not actually returning a singleton
You made the following registration: _container.AddRegistration( serviceType: typeof(ICacheManager<SettingsData>), registration: registration); And you're doing the following resolve: _container.GetInstance<SettingsCache>(); You haven't registered SettingsCache explicitly, but only ICacheManager<SettingsData>. Since SettingsCache is a concrete class, Simple Injector will resolve it as transient instance for you. The solution is to either register SettingsCache explicitly or resolve ICacheManager<SettingsData> instead. You can make a second registration with using the same Registration instance. For instance: _container.AddRegistration( serviceType: typeof(SettingsCache), registration: registration); The Diagnostic Services will warn you abo

Categories : C#

Spring Singleton Vs Singleton Design pattern - Class Loader
Using a "real" singleton is more limiting in the sense that you are then bound to be able to create only a single instance of that class (within a classloader). If you use Spring singleton-scoped beans, you can create as many "singleton" instances of that class you like (as long as the bean class is not a real singleton). Hence they are not technically the same thing.

Categories : Java

Matlab, "Assignment has more non-singleton rhs dimensions than non-singleton subscripts"
Based on the way you have declared handles.labelRGB it is a 4D array of size [160 216 3 3] however you are indexing it as a 3D array using handles.labelRGB(:,:,handles.current_slice_z) that means matlab will use linear indexing for the last two dimensions. So if, say handles.current_slice_z = 5, it returns handles.labelRGB(:,:,2,2) which is a matrix of size [160 216]. So depending on the meaning of handles.current_slice_z you either need to use handles.labelRGB(:,:,:,handles.current_slice_z) = labelRGB_slice; or handles.labelRGB(:,:,handles.current_slice_z,:) = labelRGB_slice;

Categories : Matlab

How is Meyers' implementation of a Singleton actually a Singleton
// Singleton.hpp class Singleton { public: static Singleton& Instance() { static Singleton S; return S; } private: Singleton(); ~Singleton(); }; This implementation is known as Meyers' Singleton. Scott Meyers says: "This approach is founded on C++'s guarantee that local static objects are intiialized when the object's definition is first encountered during a call to that function." ... "As a bonus, if you never call a function emulating a non-local static object, you never incur the cost of constructing and destructing the object." When you call Singleton& s=Singleton::Instance() first time the object is created and every next call to Singleton::Instance() results with the same object being returned. Main issue: subject to Destr

Categories : C++

Would an inner static runnable in a singleton block if used as wrapper for callables, if it modifies a singleton's static param?
Except when running static initializers, Java will never implicitly block. call() is a normal method call and will run synchronously in the calling thread, like any other method call.

Categories : Java

o I need to set somehow create_engine put in singleton to be like singleton?
You probably want to use scoped_session which essentially serves as a thread-local singleton, creating sessions on-demand using the provided factory function. In one module imported by all others you write: engine = create_engine(DB_URL, echo=False, pool_size=100, pool_recycle=3600) session_factory = sessionmaker(bind=engine) Session = scoped_session(session_factory) # or make it a Tornado Application property And then either use Session as an explicit factory: session = Session() session.query(...) Or use implicit method delegation: Session.query(...)

Categories : SQL

MVC 4 and autofac: DependencyResolutionException
You need to register your controller without the .As<IController>() (or you need to use .AsSelf() but this is default setting). You need to this because the framework will try to resolve your Controller with using the concrete type HomeController and not the IController interface (so the RegisterControllers method register all the controller with .AsSelf() internally). So the following registration should work builder.Register( c => new HomeController( c.ResolveNamed<IRestClient>("Url1"), c.ResolveNamed<IRestClient>("Url2"))) .InstancePerLifetimeScope(); Note: you should have this call after the RegisterControllers call.

Categories : Asp Net Mvc

Replace factory with AutoFac
Short answer: Yes. Longer answer: First, in simple cases where a class Foo is registered as the implementation for IFoo, constructor parameters or properties of type Func<IFoo> will be resolved automatically by Autofac, with no additional wiring needed. Autofac will inject a delegate that basically executes container.Resolve<IFoo>() when invoked. In more complex cases like yours, where the exact concretion returned is based on input parameters, you can do one of two things. First, you can register a factory method as its return value to provide a parameterized resolution: builder.Register<IElement>((c, p) => { var dom= p.Named<IHtml>("dom"); switch (dom.ElementType) { case "table": return new TableElement(dom); case "div

Categories : C#

Autofac constrained binding
I can't think of any neat and concise implementation of such mechanism with Autofac, but maybe you can make use of one of Autofac's meanings of selecting implementation. I'd use keyed services, which in your case would look like this: first, instead of custom attributes you'd need to define an enum enum RepositoryKind {CacheNeeded, DataNeeded} then register components marking them with those that provide Cache or data functionality, for exaple like this: builder.RegisterType<DbRepository>() .Keyed<IRepository>(RepositoryKind.CacheNeeded); builder.Register(c => new CacheRepository(c.ResolveKeyed<IRepository(RepositoryKind.CacheNeeded))) .Keyed<IRepository>(RepositoryKind.DataNeeded); builder.Register(c => new HomeController(c.ResolveK

Categories : C#

Integrating Hyprlinkr with Autofac
You don't need to write you own IHttpControllerActivator because you can register the RouteLinker itself in the container. You just need the help of the RegisterHttpRequestMessage method which makes the HttpRequestMessage resolvable from the container. So your RouteLinker registration will look something like this: builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration); builder.Register(c => new RouteLinker(c.Resolve<HttpRequestMessage>())) .InstancePerApiRequest(); Now you can depend on the RouteLinker in your controllers: public MyController : ApiController { public MyController(RouteLinker routeLinker) { //do stuff with routeLinker } }

Categories : C#

How to reset autofac container?
Autofac by default overrides previous registrations with subsequent ones. That means you don't have to do anything special apart from updating container with your new instance: var builder = new ContainerBuilder(); builder.RegisterInstance(new Sample("A")).SingleInstance(); var container = builder.Build(); var sample = container.Resolve<Sample>(); // do your test ... // new test using same container var updater = new ContainerBuilder(); updater.RegisterInstance(new Sample("B")).SingleInstance(); updater.Update(container); // overwrites existing registrations var sample = container.Resolve<Sample>(); // returns "B"

Categories : Unit Testing

property injection using autofac 3.1.1
The problem you have is Main method is static. Instanciate a class of Program and use is as non static class class Program { public ISodaService s { get; set; } static void Main(string[] args) { var resolver=SetUpContainer(); var instance=resolver.Resolve<Program>(); instance.Execute(args); } public void Execute(string[] args) { Console.Write(s.GetSoda()); Console.Read(); } private Autofac.IContainer void SetUpContainer() { var builder = new ContainerBuilder(); builder.RegisterType<Soda>().As<ISoda>(); builder.RegisterType<SodaService>().As<ISodaService>().PropertiesAutowired(); bui

Categories : C#

make autofac use TypeConverter
I dug through the autofac code and filed two issues about it: https://code.google.com/p/autofac/issues/detail?id=445 https://code.google.com/p/autofac/issues/detail?id=446

Categories : C#

Autofac not finding the most greedy constructor
Problem was that my greedy -was- getting called .. but if u looked at the greedy-ctor, you'll see that i'm doing : this(). very lame newbie error. So it was calling the greedy ctor, but before it goes into scope, it has to bubble up to the other parameterless ctor. And I kept thinking it was skipping the greedy and just hitting the parameterless. Error Between User And Keyboard.

Categories : C#

Autofac, WebAPI, and Media Formatters
If you want to let Autofac to add your custom formatter to the marked controllers then you don't need to add it to the GlobalConfiguration.Configuration.Formatters because it makes your formatter globally available and it prevents Autofac to inject properties on it. So remove the GlobalConfiguration.Configuration.Formatters.Insert call and use the following exact syntax to register your formatter: builder.Register<MediaTypeFormatter>(c => new UserMediaFormatter()) .PropertiesAutowired() .InstancePerApiControllerType(typeof(UsersController));

Categories : Asp Net Web Api

Autofac ordered list as parameter
I have a solution, that is a combination of the IOrderedEnumerable, and the ResolveOrdered<TComponent> solution from the post I linked to above. Using the AutofacExtensions Class: public static class AutofacExtensions { private const string OrderString = "WithOrderTag"; private static int _orderCounter; public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> WithOrder<TLimit, TActivatorData, TRegistrationStyle>( this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> registrationBuilder) { return registrationBuilder.WithMetadata(OrderString, Interlocked.Increment(ref _orderCounter)); } public static IOrderedEnumerable<TComponent> ResolveOrdered<TComponent>(this IComp

Categories : C#

How to register two WCF service contracts with autofac
Update (the bold text) based on @nemesv's answer: Further investigation revealed that with autofac one cannot register multiple endpoints on a single ServiceHost if one registers the WCF service contracts. (See @nemesv's answer for the correct way to do it.) Here is why: Either form of this extension method... host.AddDependencyInjectionBehavior<IService1>(_container); host.AddDependencyInjectionBehavior(t, container); ...resolves down to adding a ServiceBehavior (according to Alex Meyer-Gleaves initial announcement of WCF integration in autofac)... host.Description.Behaviors.Add(behavior); Now this Behaviors property is an instance of KeyedByTypeCollection<TItem>, which can hold only only one object of a given type. Since the behavior being added will always be an ins

Categories : C#

Autofac Register Different Implementation To Different Controllers
Have you assigned the names "TestService1" and "TestService2"? e.g. builder.RegisterType<TestService1>().As<ITestService1>().Named("TestService1"); builder.RegisterType<TestService2>().As<ITestService2>().Named("TestService2");

Categories : Asp Net Mvc

Autofac registered AuthorizationFilter calling twice
The line: builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); will register anything that implements the IAutofacAuthorizationFilter interface. So strictly speaking, you shouldn't need the second line. The second line just re-registers what Autofac is already automatically doing in the line above. So, remove the second line.

Categories : C#

Parameterless Controller Constructor Autofac
Hi i don't test that in VS 2010 because i don't have it. But in my VS 2013 works fine. public static class DependencyInjection { public static void Init() { // Create the container builder. var builder = new ContainerBuilder(); //Register controllers builder.RegisterControllers(Assembly.GetExecutingAssembly()); // Register other dependencies. builder.RegisterType<SessionStateProvider>().As<IStateProvider>().InstancePerHttpRequest(); // Build the container. var container = builder.Build(); //Configure ASP.NET MVC the dependency resolver DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } public

Categories : C#

Autofac - Register multiple decorators
You just need to register your "TransactionCommandHandlerDecoratored" ICommandHandler as a Keyed service and use that new key when registering your second DeadlockRetryCommandHandlerDecorator: builder.RegisterGenericDecorator( typeof(TransactionCommandHandlerDecorator<>), typeof(ICommandHandler<>), fromKey: "commandHandler") .Keyed("decorated", typeof(ICommandHandler<>)); builder.RegisterGenericDecorator( typeof(DeadlockRetryCommandHandlerDecorator<>), typeof(ICommandHandler<>), fromKey: "decorated"); And you will get the following output: DeadlockRetryCommandHandlerDecorator - before TransactionCommandHandlerDecorator - before MoveCustomerCommandHandler TransactionCommandHandlerDecorator - after Dea

Categories : C#

ASP.NET MVC. Autofac and multiple connection strings
One way to do it, is to create your own connection factory, and register it with autofac. Something like: interface IConnectionFactory{ SqlConnection CreateConnection(string connectionStringName); }

Categories : C#

Autofac dependency resolution error
Solution 1. You are registered a IDbContext as Named service. .Named<IDbContext>("Speed") Thus, you must use a ResolveNamed method. _container.ResolveNamed<IDbContext>("Speed"); Solution 2. You can just register a IDbContext as a type. In this case, the method Resolve() should work correctly. builder.Register<IDbContext>(c => new DbContext(ConfigurationManager.ConnectionStrings["Speed"].ConnectionString)) .InstancePerDependency();

Categories : C#

AutoFac - Registering a decorator for some of an open Generic
The problem is that when you are using the Keyed registration then you need to specify the closed service type e.g. IMyInterface<string, bool> so you cannot use an open generic there like typeof(IMyInterface<,>) However because when using the RegisterAssemblyTypes there is no API where you could get the currently registered closed type in order to register it as Keyed. So you need to implement the "assembly scanning" by hand: You need to replace your RegisterAssemblyTypes call with something like this (you probably need some more error handling in production): foreach (var type in Assembly.GetExecutingAssembly().GetTypes() .Where(type => type.GetCustomAttributes(true) .Any(attr => attr.GetType() == (typeof(MyAttribute))))) { builder.Regi

Categories : C#

Session service unique id initialization with Autofac
The problem is caused by your properties in the PushNotificationListener class. Since you create new lifetime scopes in their, within that scope a new SessionService will be created. Prevent doing this. Instead, there should only be one lifetime scope for each session. You should create a new lifetime scope (and only one lifetime scope) directly after the event is raised and before you resolve the root object. From that point on, all dependencies should be injected using constructor injection. This ensures that within that scope, there is only one SessionService.

Categories : C#

Having Automapper use services constructed by a Autofac with WebApi
This may or may not be suitable for you.. but here goes: We recently did this.. for model binders in MVC. Our model binders (on GET requests) now use Ninject-managed Services to build models. Basically, we inject a factory (using Ninject's Factories extension.. perhaps there is a similar one for Autofac) into an "AutomapperBootstrapper" class, which in turn creates Automapper mapping Profile's and adds them to Automapper. Somewhat like this: Mapper.Initialize(cfg => { cfg.AddProfile(_factory.CreateServiceViewModelMappingProfile()); // etc.. }); The mappings Profile's themselves use MapFrom(), which is evaluated each time a mapping occurs. Something like this: Mapper.CreateMap<Service, ServiceViewModel>() .ForMember(x => x.Regions, opt =

Categories : C#

FileNotFoundException when trying to load Autofac as an embedded assembly
Maybe the problem is how you try to load your EmbeddedAssembly. I have very small knowledge about how you can do it but i know the following example from code project works fine for me so maybe it will help you :-) Load DLL From Embedded Resource (If i misunderstand your question please tell me and i will delete my Answer)

Categories : C#

Autofac configuring NHibernate ISession to allow null
I'm fairly sure you'd be better off when injecting singleton lifetime-scoped ISessionFactory instead of ISession. It means that there's one instance of ISessionFactory injected to each component, and each of those components creates its own ISession (or multiple ISessions if needed). As for the keywords check, by default NHibernate connects briefly to the database when building the ISessionFactory to check for reserved keywords (that's for schema/DDL creation). You can disable that, so the first connection to the database will be made on the first ISession use.

Categories : C#

How can I disable or prevent Autofac from kicking in where it is unwanted?
Autofac chooses the constructor that has the most dependencies that it knows how to resolve. It seems that MyComponent is registered, but it is registered incorrectly: you have not specified what someNumber should be. In other words, if you just tried Resolve<MyComponent>() you would have the same problem - MyController is not the root issue here. There are a couple ways you could handle this. The easiest is to add a default constructor to MyComponent public MyComponent() : this(DateTime.Now.Millisecond) { } The second easiest is to adjust the MyComponent registration containerBuilder.Register(c => new MyComponent(DateTime.Now.Milliseconds)) .AsSelf(); You could also write the registration like this, to explicitly use the default constructor: containerBuilder.Register(

Categories : Asp Net Mvc

how to create autofac factory for dependency resolution
public class DbContextFactory { private ILifetimeScope m_RootLifetimeScope; public DbContextFactory(ILifetimeScope rootLifetimeScope) { m_RootLifetimeScope = rootLifetimeScope; } public IDbContext CreateDbContext() { if (logic for selection first dbcontext) { return m_RootLifetimeScope.ResolveNamed<IDbContext>("first"); } else if (logic for selection second dbcontext) { return m_RootLifetimeScope.ResolveNamed<IDbContext>("second"); } else { throw new NotSupportedException(); } } } //registration builder.RegisterType<DbContextFactory>().SingleInstance(); //using var factory = yourContainer.Resolve<DbContextFactory>();

Categories : C#

Autofac attribute injection failing on attributes
Your property of type IDataAccessProvider has to be public for injection to work. You can still mark DebugLogAttribute, IDataAccessProvider and it's implementation as internal if you prefer. [DebugLogAttribute] public class HOmeController : Controller { public ActionResult Index() { return View(); } } internal class DebugLogAttribute : ActionFilterAttribute { public IDataAccessProvider DataAccess { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { Debugger.Break(); } public override void OnActionExecuted(ActionExecutedContext filterContext) { Debugger.Break(); } } internal interface IDataAccessProvider {} internal class DataAccessProvider:IDataAccessProvider {}

Categories : C#

Automapper & Autofac typeconverter - does not have a default constructor
You have three problems with your current code: You need to call ConstructServicesUsing before registering any mapping as described in the linked article: The tricky thing is we need to call that method before we register mapper classes. So the correct Mapper.Initialize is the follwing: Mapper.Initialize(map => { map.ConstructServicesUsing(t => container.Resolve(t)); map.CreateMap<long?, EntityToConvertTo>() .ConvertUsing<LongToEntity<NavigationFolder>>(); }); Because your LongToEntity<T> is an open generic you cannot use AsClosedTypesOf but you need to use here also the RegisterGeneric for the registration: So change your ITypeConverter<,> registration from: builder.Register

Categories : C#

Inject WebAPI UrlHelper into service using Autofac
Best I can think of is make your service implement IAutofacActionFilter like so public class MyService : IAutofacActionFilter { private UrlHelper _urlHelper; public void DoSomething() { var link = Url.Link("SomeRoute", new {}); } private UrlHelper Url { get { if(_urlHelper == null) throw new InvalidOperationException(); return _urlHelper; } } public void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) { } public void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { this._urlHelper = actionCo

Categories : C#

Select multiple registrations for the same type in Autofac
You need to use NamedPropertyParameter instead of NamedParameter. builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>() .SingleInstance(); builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>() .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(UnauthorizedAccessException)), new NamedPropertyParameter("View", "UnauthorizedAccess") }) .SingleInstance(); builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>() .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(NotImplementedException)), new NamedPropertyParameter("View", "UnderConstruction") }) .SingleInstance(); You also may as we

Categories : C#

How do I create a Quartz.NET’s job requiring injection with autofac
The problem is that your AutofacJobFactory is not creating the ReleaseJob (you are doing this with JobBuilder.Create<ReleaseJob>() instead), so the IoC container is not aware of it's instantiation meaning dependency injection cannot occur. The following code should work: sched = schedFact.GetScheduler(); sched.JobFactory = new AutofacJobFactory(container); sched.Start(); // construct job info JobDetailImpl jobDetail = new JobDetailImpl("1Job", null, typeof(ReleaseJob )); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("1JobTrigger") .WithSimpleSchedule(x => x .RepeatForever() .WithIntervalInSeconds(5) ) .StartNow() .Build(); sched.ScheduleJob(jobDetail, trigger); Note that in this example we are not using JobBuilder.Create<Rel

Categories : Asp Net Mvc

Registering NHibernate ISession as SingleInstance in Autofac
A session keeps track of all the entities and collections it has loaded or even referenced. Keeping a session open for all the lifetime of your app results in: Extremely high memory usage Extremely slow operations (scanning the list of loaded entities, which is done automatically by many operations, takes very long when there are too many) Impossibility to recover from errors, as the session state becomes corrupted when there is one

Categories : C#

Autofac - Mvc 5 beta - DependencyResolver fails to get type
OK I figured out how to replace DependencyResolver... this seems to be an anti pattern when constructor dependency is an option. I couldn't figure out how to make it work before but I gave it another go and looks like all you need is an IComponentContext constructor parameter and Autofac will take care of it by default: public class DefaultQueryBus : IQueryBus { private readonly IComponentContext componentContext; public DefaultQueryBus(IComponentContext componentContext) { this.componentContext = componentContext; } public IEnumerable<ValidationResult> Validate<TResult>(IQuery<TResult> query) { var handlerType = typeof(IQueryValidationHandler<,>).MakeGenericType(query.GetType(), typeof(TResult)); dynamic handler =

Categories : Asp Net

Autofac Property Injection after a type is Registered
Use the WithProperty or WithProperties methods if you want to set the injections at registration rather than at initialization. ie builder.RegisterType(customType).WithProperty("PropertyName", "value");

Categories : C#

Interfaces, business logic and global.asax with Autofac
My normal approach is: Define a way to discover types in each individual assembly. Easiest approach (if you do not mind referencing Autofac in each) is to put an Autofac Module in each assembly. If you do not like that, you can define your own discovery abstraction (for example, MEF-like attributes). Discover all assemblies. Easiest approach is to scan the bin folder, but you can use some custom configuration. I haven't checked latest versions of Autofac add anything in terms of module discovery, but previously I did it manually. Use previously defined type discovery approach to register all relevant types from each discovered assembly.

Categories : C#

Create an Autofac service around a background thread or task
Maybe, you can use NCron (https://code.google.com/p/ncron/). NCron is a light-weight library for building and deploying scheduled background jobs. Also, you can use Autofac integration to perform dependency injection for your NCron jobs (https://code.google.com/p/ncron/wiki/DependencyInjection).

Categories : Asp Net



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.