Does Unity have Autofac's equivilent of Owned<> to force new instance to be created - unity-container

The project I'm on requires we use Unity. The lifetime managers are correctly set so this is not an issue with setting a lifetime manager. We have a special case where I need to resolve a service but it needs to freshly resolve every dependency as if it was the original request. In Autofac I can do this by injecting an Owned. Does Unity support anything like that or is there a way I can call Resolve and get a fresh set of injections?

Unity doesn't have equivalent of Autofac's Owned<> feature.
As for your problem, I think factories could solve it. You can write your own factory or use Unity Automatic Factories feature. More info on msdn.

I ended up using a Marker interface and registering that interface with a different scope. Then when I must have a new instance and not a shared instance I use the other interface.

Related

When use Extension class, when use Compiler Passes in Symfony?

What is the point of using compiler passes in Symfony?
When we should use Extension class and when Compiler Passes in Symfony?
They come with services definition.
By creating a compiler pass, you are able to update the arguments passed to services.
It's most often done with tagged services.
Also, It can be used for :
Creating new services that require information about other defined services before being defined.
Swapping or adding arguments to a service that you did not write.
Creating and modifying parameters in the container.
I used a compiler pass to register a Factory that make me able to override the doctrine Repository.
You can see the code for more comprehension of how it works:
https://gist.github.com/chalasr/77be8eee5e3ecd3c06ec
Update
Thank's to #Sruj, I added the part I've forgotten about the Extension
Extension are part of dependency injection too, especially of the configuration.
Its primary role is to load the configuration of services across the bundles of your application.
Instead of load your configuration manually by using imports, you can create an extension that does it for you. All your services configuration are registered from your bundle and shared in your whole application.
When you register a vendor in your app configuration, the service container extension of the vendor is invoked.
See "Importing configuration via container extensions" part of the documentation

Lazy loading dependencies with symfony DI

Currently I've got a Symfony2 DI container instance ready with a service and all it's dependencies. Lets say for example I have a Car class and it has Engine and Lights as dependencies.
In my current setup both these dependencies are automatically created through setter injection when the Car object is created, but it might very well be that my Car object won't need it's lights this time around thus it doesn't explicitly need to create an instance of this dependency.
Is there a way to achieve this in Symfony DI? Thus only creating an instance of the Lights object when needed? My guess is it'll be some sort of Proxy implementation like Doctrine has but as far as i've seen it doesn't exist in Symfony DI.
Inject the dedendencies that are mandatory through the Constructor via your services.yml, automatically.
If you have optional dependencies inject them through a setter in your Controller when you need them.
$this->container->get('cars')->setLights(new \Namespace\Lights());
Of course your Cars class must be designed like so and you have to direct the injections yourself in your controller, or whereever needed, code.
Question is already answered, but for who needs this functionality, lazy services are implemented in Symfony 2.3.
You need to install the ProxyManager bridge.
You can find official documentation here.
A very interesting question, but I don't think it's possible within Symfony2's Dependency Injection Container. The container is only aware of what you tell it - in this case, you have a dependency that's conditional on a specific use-case. Plus, the registration of services happens early on in the app's life, so I don't see how you could get this to work.
Maybe you should use the Factory pattern. Register a CarFactory as a service, and then when fetching a Car instance, you can specify that it should include a Light dependency.
Can I ask why you want to achieve this? There may be a simpler solution.
It's not a pretty workaround, but you can try injecting the whole DIC, then getting the Light and Engine services when neccessary.
I was thinking about something like this method in the Car class:
protected function getLightService()
{
if (!$this->light) { //so we reuse the first instance
$this->light = $this->dic->get("car.light");
}
return $this->light;
}

Make EnterpriseLibrary use the UnityContainer created through UnityBootstrapper

My application subclasses UnityBootstrapper which creates the default UnityContainer.
We are also using EnterpriseLibrary and what to force it to use our unity container created in the bootstrapper and not create it's own.
Is this an acceptable practice? Our reasoning is that we want to be able to access caches (we have multiple) created via injection to our classes without directly having to reference the enterprise library.
I've seen different things from using UnityContainerConfigurator and AddNewExtension() as well as just setting EnterpriseLibraryContainer.Current. I'm having a hard time understanding the difference and which is the correct solution.
I think using an explicitly instantiated container is perfectly acceptable. Enterprise Library is designed to allow you to switch and use other dependency injection frameworks instead of Unity or you can BYOC (bring your own [Unity] container).
Basically, you just need to create the Enterprise Library extension and add it to the container and then set the container as the service locator that Enterprise Library will use.
In this example I have an app.config with a CacheManager configured called "My Cache Manager":
EnterpriseLibraryCoreExtension coreExtension =
new EnterpriseLibraryCoreExtension();
container.AddExtension(coreExtension);
IServiceLocator locator = new UnityServiceLocator(container);
EnterpriseLibraryContainer.Current = locator;
var cacheManager1 = container.Resolve<CacheManager>("My Cache Manager");
var cacheManager2 = EnterpriseLibraryContainer.Current
.GetInstance<CacheManager>("My Cache Manager");
Debug.Assert(ReferenceEquals(cacheManager1, cacheManager2));

How Orchard CMS does the logging?

I'm working with Orchard CMS and it is better CMS for me. I want to understand how it does the logging and whether I can add my own logging or not. I saw that Orchard uses NullLogger class and it does no work. I've opened the App_Data.Logs folder and have seen that there are the log files. But how? I searched in code where is the trick that replaces NullLogger with log4net (I guess this is log4net, because the log format and the formatting for log4net.config are very similar) but I haven't found this.
Can somebody answer me:
How Orchard does the logging?
Whether I can add my own logger and if yes what best practices exist to do this?
Thanks, Andrey.
An Autofac module (Orchard.Logging.LoggerModule to be precise) handles that. Basically - it scans each dependency and fills all properties of type ILogger with a reference to appropriate logger instance. Each dependency gets its own logger with name equal to full type name (including namespace) of a containing class.
The NullLogger is just a placeholder so accessing the property would not throw NullReferenceExceptions before the property is being set by Autofac.
Extending the default logging is a rather complicated task as it would involve doing three things:
create a custom implementation of ILoggerFactory (just like the default Orchard.Logging.CastleLoggerFactory) and
create an Autofac module that registers that implementation in the container (like the mentioned LoggerModule does)
suppress the current default logging module by decorating your new one with [OrchardSuppressDependency("Orchard.Logging.LoggingModule")]
UPDATE
Just realized I haven't addressed the most important part of the question here:)
Yes, Orchard uses log4net so you may alter the default settings via Config/log4net.config file.
There is a great article on how Orchard Logging works. (I am not sure if it is ok to copy and paste the entire article). This is the link: Injection Logger in Orchard
So the trick is this:
Whenever a class requires a Logger instance, all it needs to do is to
declare a ILogger property, that’s it. And later, in your class, you
can use this property to Logging at anytime
And how is this done?
When Orchard web application startup, the OrchardStarter will be used
to do most of the registration work.
In a few words, it looks all the code in all projects, gets all the classes that use an ILogger property, and implements it for you (if not implemented), using Castle's logger factory.

ASP.NET and Unity

First of all, is there a complete reference on Microsoft Unity?
I noticed today that, when I call "Configure" on the "UnityConfigurationSection" it configures and prepares all configuration mappings.
What if a class has a dependency on an object registered inside Unity. Does this class itself needs to be registered by Unity so that, Unity injects its dependency?
I am afraid that Unity would not inject a dependency on an Object, if that object is not registered into Unity. This is the case with "Page" class in ASP.NET.
Thanks
Unity has some well defined default behavior when working on classes that aren't registered ahead of time.
In the absence of registration, the container will look for the longest constructor, and it'll also look for attributes on the type ([Dependency] being the main one) to figure out what properties to inject.
If you don't want to use the attributes or the defaults don't match what you want, you'll need to configure the container to do the what you want.

Resources