How to make Autofac perform property injection in Orchard CMS - asp.net

Is it possible to do property injection with the OrchardCMS?
I know that Orchard uses Autofac and that Autofac does do property injection, but I need to know how to do property injection for the IOrchardServices interface.
Our team is looking at Orchard but our code base is all in ASP.NET 4.0 WebForms and so we will continue to serve aspx pages and slowly migrate those said pages into Orchard as time permits.
With that, we'll need a way to get access to the OrchardServices object. I'm thinking that this is something I'd have to come up on my own. Does any one have any good examples of performing property injection in Orchard?

It's pretty simple - look into the source how it's done with ILogger interfaces and do the same for IOrchardServices. The source file is Orchard.Framework/Logging/LoggingModule.cs. It's exactly what you are looking for, I guess.
Everything is being done via Autofac module (implementation of Autofac.Module class). What that class does is to:
register the implementation of ILogger interfaces (Load method) and
get properties of the processed object and set appropriate ones to object resolved from the container (AttachToComponentRegistration method).
Pretty simple. Autofac modules are a nice way to plug into the DI process.
It would be enough just to copy that source file to your custom Orchard module and changing ILogger to IOrchardServices (and, of course the registered class). The class I mentioned makes use of factory pattern to create instances, but you can change that to simple object creation via new and get rid of the factory-related things.

Related

Autofac resolve within class library

I have a web forms application (myWebForms)
I have a class library project (myClassLibrary) that has a class called "myClass"
WebForms references myClassLibrary
I have added Autofac references to the web forms application, set the global asax to resolve "myClass" etc...
I can see that in my aspx code behind, the public property I added for AutoFac, is instantiated correctly by AutoFac.
All this is great so far, however, my actual project is a lot more complex than this, and what I need to do is have access to the resolved "myClass"
From within myClassLibrary
How do I achive this? (do I inject the container into myClass from the web forms project?, do I somehow reference the web forms global property, or do I build the container again within myClassLibrary?)
First, I'd recommend checking out the Autofac documentation on web forms and quick starts. I think you may have a lot of questions answered by doing that, though I understand it's a lot. DI is complicated, and I'm afraid that providing just a "quick answer" here may lead you to an incorrect understanding of what's going on.
Autofac quick start
ASP.NET Web Forms Integration
Working example of web forms integration
In general...
You register types with Autofac that you want to inject. This includes all the types your web forms will need as well as all the dependencies those types will need.
Autofac, via its integration, will resolve dependencies and put them in your web forms. If those objects also have dependencies (e.g., constructor parameters), then Autofac will also figure those out automatically and plug them in.
Say your web form needs a property called IEmailSender...
public IEmailSender EmailSender { get; set; }
Your email sender object may need some other dependency, like a network socket factory or something.
public EmailSender(ISocketFactory socketFactory)
You would register both of these in the container. It doesn't matter which assembly they come from. You have to register them into the Autofac container for it to work.
builder.RegisterType<EmailSender>().As<IEmailSender>();
builder.RegisterType<TcpFactory>().As<ISocketFactory>();
When your web form gets the IEmailSender, Autofac will resolve the TcpFactory first, then provide that in the constructor of EmailSender, then that will be handed to your web form.
Again, a lot of this is covered in the docs and examples. While I realize there's a lot and it can be overwhelming, I strongly urge you to walk through that info because it can save you a lot of time and pain in the long run.

IoC in MVP Asp.NET

I'm developing a application using MVP and I have a question about How inject my dependencis in my presenters class. Because my presente receve too an instance of the my view. I thought of create a viewbase and inside it I create my dependencies instances and inject it in my presenter instance. Could also have a HttpModule that intercept the calls to page and then I could inject my dependencies. I have some ideas but none I can inject my view in constructor only I can inject my view in mey presente by property. Someone have any ideas how do you do to inject my dependencies and my view in constructor of the presenter?
To implement MVP inside of webforms is a little less perfect than MVC, mostly from the fact you cannot have a custom build factory for your page which means at some level you need to couple your page to the IOC framework, generally at a basepage level.
I wrote a blog on achieving this. Creating a generic Model-View-Presenter framework I've expanded upon this to allow me to implement many views and have a single presenter mediate many views but haven't had the time to blog about that. That's more of an advanced usage anyway, my source here should get you up and running easily. My post specifically references StructureMap 2.5.3 but it can be easily adapted to suit any IOC framework that supports the "BuildUp" type of functionality.

Handling Dependency Injections - Where does the logic go?

I'm working on an ASP.Net website along with a supporting Class Library for my Business Logic, Data Access code, etc.
I'm EXTREMELY new and unfamiliar with the Unity Framework and Dependency Injection as a whole. However, I've managed to get it working by following the source code for the ASP.NET 3.5 Portal Starter Kit on codeplex. But herein lies the problem:
The Class Library is setup with Unity and several of my classes have [Dependency] attributes on their properties (I'm exclusively using property setter injections for this). However, the Global.asax is telling Unity how to handle the injections....in the Class Library.
Is this best practice or should the Class Library be handle it's own injections so that I can re-use the library with other websites, webapps or applications? If that is indeed the case, where would the injection code go in this instance?
I'm not sure how clear the question is. Please let me know if I need to explain more.
Though not familiar with Unity (StructureMap user) The final mappings should live in the consuming application. You can have the dll you are using define those mappings, but you also want to be able to override them when needed. Like say you need an instance of IFoo, and you have one mapped in your Class Library, but you've added a new one to use that just lives in the website. Having the mappings defined in the site allows you to keep things loosely coupled, or else why are you using a DI container?
Personally I try and code things to facilitate an IOC container but never will try and force an IOC container into a project.
My solution breakdown goes roughly:
(Each one of these are projects).
Project.Domain
Project.Persistence.Implementation
Project.Services.Implementation
Project.DIInjectionRegistration
Project.ASPNetMVCFrontEnd (I use MVC, but it doesn't matter).
I try to maintain strict boundaries about projects references. The actual frontend project cannot contain any *.Implementation projects directly. (The *.implementation projects contain the actual implementations of the interfaces in domain in this case). So the ASPNetMVCFrontEnd has references to the Domain and the DIInjectionWhatever and to my DI container.
In the Project.DIInjectionWhatever I tie all the pieces together. So this project has all the references to the implementations and to the DI framework. It contains the code that does the registering of components. Autofac lets me breakdown component registration easily, so that's why I took this approach.
In the example here I don't have any references to the container in my implementation projects. There's nothing wrong with it, and if your implementation requires it, then go ahead.

How to sort this Repository pattern and ASP.Net website architecture?

I am Creating a new ASP.Net website "not mvc", and willing to make the data access layer has 2 versions, one using the Linq to Sql and another one using ad.net entity framework.
Note: kigg is doing the same but in MVC website and too complex than i want.
I learned that the best pattern to achieve my goal is using repository design pattern.
My question is, where in my code and layers "dal, bal, ui" the switch will happen? in other words where i will change the code to apply the linq to sql to ado.net entity framework or vice versa.
I wrote:
IRepository repository;
Then in the class constuctor
repository = MyRepositoryLinqToSql();
can some one teach me this part architecture wise?
If you want to create a pluggable architecture to be able to swap out the repository layer on the fly then you will need to create everything behind an interface and then use something like StructureMap to dynamically swap in what you need when you need it.
You would want to define a repository class like AccountRepository. One for linq to sql LSAccountRepository and EFAccountRepository. Both of these would inherit from IAccountRepository and have methods such as GetAccountByID, SaveAccount, DeleteAccount, etc.
Then using StructureMap you would have syntax like so to load the appropriate repository based on the system that you are loading in.
IAccountRepository _accountRepository = ObjectFactory.GetInstance();
Then via your configuration you can specify the default implementation of IAccountRepository and swap this out to point to either implementation at any time.
If this is too complex then a dependancy injection patten can be used in that you can have a method with a parameter of IAccountRepository. This method would be called by a controller (MVP or MVC) and you can pass in the appropriate reference at that time. This way you do not directly instantiate the repository inside of the method that might need one repository vs. another.
Even if you do decide to do a DI pattern you can still use StructureMap. When you instantiate an object that has other dependancies in it that StructureMap knows about (in the constructor) then StructureMap will also load up those objects as well. Then the caller of the object that has the method that you need will be the only loose coupling that is needed as StructureMap will dynamically take care of the dirty work for you.
This is a bit of a heavy question to answer, but you could add a constructor that takes an IRepository instance as a parameter and use that within the class itself. As for how to populate it, please do some research on Inversion of Control containers such as Spring and Windsor. These tools take configuration details about which specific implementations you want to use and then automatically pass these instances to the constructors and properties of classes.
For example, you can indicate which version of IRepository you want to use in your app.config file, and whereever this appears in a constructor an instance of your chosen class will be passed in.
I think you're looking for "Dependency Injection" solution.
Chack this out:
Unity Dependency Injection Video using ASP.NET Webforms - Ninject and Autofac IoC Too!
Unity And Asp.Net WebForms

How to hide the real IoC container library?

I want to isolate all my code from the IoC container library that I have chosen (Unity). To do so, I created an IContainer interface that exposes Register() and Resolve(). I created a class called UnityContainerAdapter that implements IContainer and that wraps the real container. So only the assembly where UnityContainerAdapter is defined knows about the Unity library.
I have a leak in my isolation thought. Unity searches for attributes on a type's members to know where to inject the dependencies. Most IoC libraries I have seen also support that. The problem I have is that I want to use that feature but I don’t want my classes to have a dependency on the Unity specific attribute.
Do you have any suggestions on how to resolve this issue?
Ideally I would create my own [Dependency] attribute and use that one in my code. But I would need to tell the real container the search for my attribute instead of its own.
Check out the Common Service Locator project:
The Common Service Locator library
contains a shared interface for
service location which application and
framework developers can reference.
The library provides an abstraction
over IoC containers and service
locators. Using the library allows an
application to indirectly access the
capabilities without relying on hard
references. The hope is that using
this library, third-party applications
and frameworks can begin to leverage
IoC/Service Location without tying
themselves down to a specific
implementation.
Edit: This doesn't appear to solve your desire to use attribute-based declaration of dependency injection. You can either choose not to use it, or find a way to abstract the attributes to multiple injection libraries (like you mentioned).
That is the basic problem with declarative interfaces -- they are tied to a particular implementation.
Personally, I stick to constructor injection so I don't run into this issue.
I found the answer: Unity uses an extension to configure what they call "selector policies". To replace the attributes used by Unity, you just code your own version of the UnityDefaultStrategiesExtension class and register you own "selector policies" that use your own attributes.
See this post on the Unity codeplex site for details on how to do that.
I'm not sure that it's going to be easy to do the same if I switch to another IoC library but that solves my problem for now.
Couldn´t you just setup your configuration without the attributes, in xml. That makes it a bit more "unclear" I know, personally I use a combination of xml and attributes, but at least it "solves" your dependency on unity thing.

Resources