Tag: suggestions

Autofac Modules and Code Organization

Organizing Code With Autofac Modules

What are Autofac Modules?

I’ve been writing a little bit about Autofac and why it’s rad, but today I want to talk about Autofac modules. In my previous post on this, I talk about one of drawbacks to the constructor dependency pattern is that at some point in your application, generally in the entry point, you get allllll of this spaghetti code that is the setup for your code base.

Essentially, we’ve balanced having nice clean testable classes with having a really messy spot in the code. But it’s only ONE spot and the rest of your code is nice. So it’s a decent trade off. But we can do better than that, can’t we?

Autofac modules!

We can use Autofac modules to organize some of the code that we have in our entry point into logical groupings. So an Autofac module is an implementation of a class that registers types to our dependency container to be resolved at a later time. You could do this all in one big module, but like many things in programming, having some giant monolothic thing that does ALLLL the work usually isn’t the best.

An Example of Converting to Autofac Modules

Let’s create a simple application as an example. I’ll describe it in words, and then I’ll toss up some code to show a simple representation if it. We’ll assume we’re using dependencies passed as interfaces via constructors as one of our best practices, which makes this conversion much easier!

So our app will have a main window with a main content area and a header area. These will be represented by three objects. Our application will also have a logger instance that we pass around so classes that need logging abilities can take an ILogger in their constructor. But our logger will have some simple configuration that we need to do before we use it.

Let’s assume to start our Program.cs file looks like this:

internal sealed class Program
{
    private static void Main(string[] args)
    {
        var logger = new FileLogger();
        logger.LogLevel = LogLevel.Debug;
        logger.FilePath = "log.txt";

        var header = new FancyHeader(logger);
        var content = BoringMainContent();
        var window = new MainWindow(header, content);
        window.Show();
    }
}

Before getting comfortable with Autofac, my initial first step would be to logically group things in the main method. In this particular case, we have something simple and surprise… it’s all grouped. But my next step would usually be to pull these things out into their own methods. I do this because it helps me identify if my groupings make sense and where my dependencies are. Let’s try it!

internal sealed class Program
{
    private static void Main(string[] args)
    {
        var logger = InitializeLogging();
        var window = InitializeGui(logger);
        window.Show();
    }

    // no params passed in, so no dependencies
    // return value is an ILogger, so we have a
    // logical grouping that will provide us a logger
    private static ILogger InitializeLogging()
    {
        var logger = new FileLogger();
        logger.LogLevel = LogLevel.Debug;
        logger.FilePath = "log.txt";
        return logger;
    }

    // only parameter is a logger, so that's our dependency
    // return value is a window, so this grouping provides
    // a window for us
    private IWindow InitializeGui(ILogger logger)
    {
        var header = new FancyHeader(logger);
        var content = BoringMainContent();
        var window = new MainWindow(header, content);
        return window;
    }
}

Alright cool. So yes, this is a bit of extra code compared to the initial example, but I promise you grouping these things out into separate methods as a starting point when you have a LOT of initialization logic will help a ton. Once they are in methods, you can pull them out into their own classes. Refactoring 101 for single responsibility principle going on here 😉 BUT, we’re interested in Autofac. So what’s the next step?

We have two logical groupings going on here in our example. One is logging and the other is for the GUI. So we can actually go ahead and make two Autofac modules that do this work for us.

public sealed class LoggingModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder
            .RegisterType<FileLogger>()
            .AsImplementedInterfaces() // FileLogger will be resolved as an ILogger
            .SingleInstance() // we only ever need to use one logger instance for our app
            .OnActivated(x =>
            {
                // this handles our extra setup we had for this object
                x.Instance.LogLevel = LogLevel.Debug;
                x.Instance.FilePath = "log.txt";
            });
    }
}

public sealed class GuiModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder
            .RegisterType<FancyHeader>() // this has a dependency on ILogger, but autofac will figure it out for us
            .AsImplementedInterfaces() // FancyHeader will be resolved as IHeader
            .SingleInstance(); // we only ever need to use one instance for our app
        builder
            .RegisterType<BoringMainContent>()
            .AsImplementedInterfaces() // BoringMainContent will be resolved as IContent
            .SingleInstance(); // we only ever need to use one instance for our app
        builder
            .RegisterType<MainWindow>() // Autofac will resolve our IHeader and IContent dependencies for us
            .AsImplementedInterfaces() // MainWindow will be resolved as IWindow
            .SingleInstance(); // we only ever need to use one instance for our app
    }
}

And those are our two logical groupings for modules! So, how do we use this and what does our Main() method look like now? I’ll demonstrate with one way that works for a couple modules, but I want to follow up with another post that talks about dynamically loading modules. If you can imagine this scenario blown out across MANY modules, you’ll understand why it might be helpful.

The idea for our Main() method is that we just want to resolve the one main dependency manually and let Autofac do the rest. So in this case, it’s our MainWindow.

private static void Main(string[] args)
{
    // create an autofac container builder
    var containerBuilder = new ContainerBuilder();

    // manually register our two new modules we made
    containerBuilder.RegisterModule<LoggingModule>();
    containerBuilder.RegisterModule<GuiModule >();

    // create the dependency container
    var container = containerBuilder.Build();

    // resolve and use our main dependency by it's interface
    // (because we shouldn't care what the implementation is...
    // that was up to the configuration via modules!)
    var window = container.Resolve<IWindow>();
    window.Show();
}

In Summary…

This example showed us how to group your main initialization logic out into groups that would play nice as Autofac modules. In a really simple example, having modules might look like bloated extra code, but it already illustrated that your entry point is very simple and follows a pattern to extend (just register another module for more dependencies… and I’ll add more on this later). There’s also an obvious way to group more new logic into your application for dependencies! So discussed logging and GUI initialization, but you could extend this to:

  • User Settings
  • Analytics/Telemetry
  • Error Reporting
  • Database Configuration
  • Etc… Just add more modules!

Sometimes the pain of having a really hectic entry point isn’t realized until you’ve had to work on teams where people are modifying the same beast of an entry point all the time:

  • Simple merge conflicts in your “using” statements… Because there’s hundreds of lines of using statements at the top of the file
  • Visual studio actually CANNOT use intellisense properly when the file gets too unwieldly
  • The debugger cannot resolve variables properly when the main entry point gets too big
  • Merging and auto-conflict resolution sometimes results in code just getting blown away in the entry point… And good luck finding what went wrong in your thousands of lines of initilization

So what’s next? Well, if you keep building out your app you might notice you have tons of modules now. Your single GUI module might have to get broken out into modules for certain parts of the GUI, for example, just to keep them more manageable. Maybe you want plugins to extend the application dynamically, which is really powerful! Our method for registering modules just isn’t really extensible at that point, but it’s very explicit. I’ll be sharing some information about automatic Autofac module discovery and registration next!


Recognition – Weekly Article Dump

Recognition - Weekly Article Dump (Image from http://www.sxc.hu/)

Recognition – Weekly Article Dump

Not all of the articles this week touch on recognition, and to be honest, I didn’t pick it as a theme for the articles either. Recognition is more a topic of discussion that’s come up over the last week at Magnet Forensics, where I work. Being a team lead and part of the management team at Magnet, I’m often part of conversations about motivation. Providing recognition is an excellent way to motivate your staff and shows that you truly appreciate them. We’ve been trying to get better at recognizing staff for doing an awesome job–especially because we have so many awesome people working with us. It’s pretty obvious with our Profit Hot 50 placement that we’ve got some kick-ass people.

Recognition, whether it’s one-on-one or in a public setting, has a huge impact. I don’t even mean recognition in the form of compensation (e.g. bonus or salary raise). Just giving someone recognition for the awesome work they’ve done–plain and simple. It’s a great way to let someone know that their hard work and commitment isn’t going unnoticed. Sure, if they’re developing products, making sales, or acquiring leads there are certain metrics that indicate they’re doing a great job, but recognition is that additional feedback you can provide to really drive the point home. It motivates people and often has a bigger impact than providing compensation.

I want to make a conscious effort to try and recognize some of my colleagues on Dev Leader, going forward, when the opportunity presents itself. I’m always learning from the people I work with and there’s always something great I can say about them. Why not give them a public acknowledgement?

I also have a little surprise coming from a friend and colleague of mine, Tayfun Uzun, early next week, so keep your eyes open for that!

Articles

  • Job Titles and Responsibilities: Last week I wrote about my thoughts on the true role of job titles. As soon as you start to look at your job title as something that defines your limits, you’re on the wrong path. Your job title should define what you’re responsible for, but it’s by no means supposed to put limits on what you can do. Check it out and let me know what you think! Do you feel like job titles should keep people to only a certain set of tasks? Do you feel like having set responsibilities is useful at all?
  • How Strong Is Your Bench: Having a successful company is all about having the right people on board. Sylvia Hewlett writes about what it means to have a rock solid roster within your company. Some of the things include avoiding hiring clones of people exactly like yourself and instead trying to diversify the skill sets within your company. Absolutely true!
  • 8 Steps for Engineering Leaders to Keep the Peace: There seems to be a natural tendency for engineers or people implementing components of a product to push back on product managers or people who decide how a product/service should be. Steven Sinofsky discusses the importance of being an effective engineering leader and ensuring proper communication between engineering leaders and people like PMs or founders. Open and transparent communication is key and helps remind the other party that you do in fact have the same end-goal.
  • Top Tips To Being a Great Mentor: In this article, James Caan provides four key points for being a better mentor. Patience, honesty, positivity, and focus are the four pillars that James describes. Patience and honesty, in my opinion, are the most important but I certainly agree with all four!
  • Leading a Customer-Centric Transformation: Hopefully it’s not surprising, but customers are what your business should be geared toward. As a result, it makes sense that leading customer-centric employees would be beneficial. Don Peppers outlines six things to focus on to make this transformation necessary. It ties in with my post on avoiding organizational silos.
  • The Dark Side Of Software Development That No One Talks About: Don’t be scared that this article mentions software development if you’re not a programmer! It touches on some great points about having a career in software development, so even if you’re not a developer yourself, it sheds some light on some more broad issues. John Sonmez writes about why software developers seem like jerks sometimes and what you can do about it. It seems to boil down to intelligence being a deciding factor for how well you program, so lording your intelligence over other people makes you superior. And because our own intelligence is something we all hold personally, we can get defensive about it pretty easily. John suggests that part of the solution is trying to simplify aspects of software development.
  • How to Win Loyalty From Other People: To be a successful leader, the people you lead need to be loyal to you. Deepak Chopra writes about seven suggestions for building up loyalty and among them “abstaining from disloyalty” is one of my favourites. If you act differently behind people’s backs compared to when you’re leading them, it may come back to bite you later. It’s also crucial to pay attention to each individual’s personal differences to ensure they feel understood.
  • Strategies for Dealing with Randomness in BusinessDon Peppers twice on the list this week! Things in life and business aren’t always predictable for us. It’s just how things are. Are you properly set up to deal with uncertainty in your business though? Remain agile!
  • 10 Quotes All Entrepreneurs Should Memorize: How about some quotes to motivate you? Joel Peterson lists 10 great quotes for entrepreneurs, but I think they carry over to anyone working in a startup. Don’t be afraid to fail and keep moving forward to improve!
  • The Two Biggest Distractions – And What to Do About Them: Distractions are ever-increasing in the workplace, but have you ever considered the differences between the different types of distractions? Daniel Goleman discusses two very different types of distractions: sensory and emotional. I hadn’t really noticed it, but often we find ourselves consciously trying to avoid sensory distractions. If our phone lights up or we get an email notification, we either give in or we make an effort to try and reduce the effect of these distractions. But an emotional distraction is much worse. If something tweaks your emotions the wrong way at work, it often has a bigger impact and it’s usually unexpected.

My take away point for this week regarding recognition: Do it early and do it often. Remember to follow Dev Leader on social media outlets to get these updates through the week!

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+

You can also check out Dev Leader on FlipBoard.


  • Subscribe to Blog via Email

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress